#include #include #include #include #include #include #include #include #include "common.h" #define FAIL_TO_CLEANUP(cond, jmp_to) \ if (cond) { \ perror(#cond); \ ret = EXIT_FAILURE; \ goto jmp_to; \ } int main(void) { int ret; int shm_fd = -1; void *shm_ptr = MAP_FAILED; sem_t *sem_c2s = SEM_FAILED; sem_t *sem_s2c = SEM_FAILED; /* Create or open shared memory */ FAIL_TO_CLEANUP((shm_fd = shm_open(SHM_NAME, O_CREAT | O_RDWR, 0600)), cleanup); if (shm_fd == -1) { perror("shm_open"); goto cleanup; } if (ftruncate(shm_fd, SHM_SIZE) == -1) { perror("ftruncate"); goto cleanup; } shm_ptr = mmap(NULL, SHM_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0); if (shm_ptr == MAP_FAILED) { perror("mmap"); goto cleanup; } /* Create semaphores (initialize to 0) */ sem_c2s = sem_open(SEM_C2S_NAME, O_CREAT, 0600, 0); if (sem_c2s == SEM_FAILED) { perror("sem_open c2s"); goto cleanup; } sem_s2c = sem_open(SEM_S2C_NAME, O_CREAT, 0600, 0); if (sem_s2c == SEM_FAILED) { perror("sem_open s2c"); goto cleanup; } printf("Server: waiting for client...\n"); while (1) { /* Wait for client to write filename */ if (sem_wait(sem_c2s) == -1) { perror("sem_wait c2s"); break; } /* Read filename from shared memory (ensure NUL) */ char filename[SHM_SIZE]; memset(filename, 0, sizeof(filename)); memcpy(filename, shm_ptr, sizeof(filename) - 1); /* If client sent special "EXIT" filename, break loop and cleanup */ if (strcmp(filename, "EXIT") == 0) { /* Notify client and exit */ const char *msg = "Server shutting down."; size_t len = strlen(msg) + 1; if (len > SHM_SIZE) len = SHM_SIZE; memcpy(shm_ptr, msg, len); sem_post(sem_s2c); break; } /* Try open file */ FILE *f = fopen(filename, "rb"); if (!f) { char errbuf[SHM_SIZE]; snprintf(errbuf, sizeof(errbuf), "Error opening file '%s'\n", filename); size_t len = strlen(errbuf) + 1; if (len > SHM_SIZE) len = SHM_SIZE; memcpy(shm_ptr, errbuf, len); sem_post(sem_s2c); continue; } /* Read file content and write to shared memory (truncate if too large) */ size_t total = 0; while (!feof(f) && total < SHM_SIZE - 1) { size_t toread = SHM_SIZE - 1 - total; size_t r = fread((char *)shm_ptr + total, 1, toread, f); total += r; if (r == 0) break; } ((char *)shm_ptr)[total] = '\0'; /* ensure NUL */ if (!feof(f) && total == SHM_SIZE - 1) { /* truncated */ const char *note = "\n[Output truncated: file larger than shared memory]\n"; size_t note_len = strlen(note); if (note_len + 1 < SHM_SIZE) { size_t copy_pos = SHM_SIZE - 1 - note_len; memcpy((char *)shm_ptr + copy_pos, note, note_len); ((char *)shm_ptr)[SHM_SIZE - 1] = '\0'; } } fclose(f); /* Signal client that data is ready */ if (sem_post(sem_s2c) == -1) { perror("sem_post s2c"); break; } } cleanup: if (sem_c2s != SEM_FAILED) sem_close(sem_c2s); if (sem_s2c != SEM_FAILED) sem_close(sem_s2c); if (shm_ptr != MAP_FAILED) munmap(shm_ptr, SHM_SIZE); if (shm_fd != -1) close(shm_fd); return 0; }