#include #include #include #include #include #include #include #include #define BUFFERSIZE 200 #define SEMKEY 251 #define SHMKEY 231 #define SHMSIZE 1024 #define FILENAME "abc.txt" union semun { int val; struct semid_ds *buf; unsigned short *array; }; int main() { char buf[BUFFERSIZE]; int sem_id = semget(SEMKEY, 1, IPC_CREAT | 0600); union semun sem_val; sem_val.val = 0; semctl(sem_id, 0, SETVAL, sem_val); int shm_id = shmget(SHMKEY, SHMSIZE, IPC_CREAT | 0600); char *shm_addr = (char *)shmat(shm_id, NULL, 0); memset(shm_addr, 0, SHMSIZE); char *cur = shm_addr; FILE *fp = fopen(FILENAME, "wb"); if (fork() == 0) { int isend = 0; int line = 1; printf("\n#line%d$ ", line); while (!isend && fgets(buf, BUFFERSIZE, stdin) != NULL) { line++; printf("\n#line%d$ ", line); if (buf[0] == 'Q' && strlen(buf) <= 2) { isend = 1; printf("\nExit...\n"); } else { memcpy(cur, buf, strlen(buf)); cur += strlen(buf); struct sembuf sem_op = {0, 1, 0}; semop(sem_id, &sem_op, 1); } } *cur = -1; shmdt(shm_addr); exit(0); } else { while (1) { struct sembuf sem_op = {0, -1, 0}; semop(sem_id, &sem_op, 1); if (*cur == -1) break; int i; for (i = 0; *cur != '\n'; cur++, i++) buf[i] = *cur; cur++; buf[i] = '\n'; buf[++i] = 0; fwrite(buf, strlen(buf), 1, fp); } fclose(fp); wait(NULL); shmdt(shm_addr); shmctl(shm_id, IPC_RMID, NULL); } return 0; }