作業(yè)社區(qū)
探索學(xué)習(xí)新天地,共享知識(shí)資源!
weixin_慕九州3042664 的學(xué)生作業(yè):
#include #include #include #include #include #include #include #include #define PATH “.” #define MAGIC 0xDEAD #define SEM_SIZE 2 int main(int argc, char *argv[]) { if(argc != 2) { fprintf(stderr, “Usage: [%s] \n”, argv[0]); exit(EXIT_FAILURE); } key_t key = ftok(PATH, MAGIC); if(key == -1) { perror(“ftok()”); exit(EXIT_FAILURE); } int semid = semget(key, SEM_SIZE, IPC_CREAT | 0644); if(semid == -1) { perror("semget()"); exit(EXIT_FAILURE); } // sem[0]: child can write // sem[1]: parent can write '\n'. unsigned short values[SEM_SIZE] = {0, 0}; int ret = semctl(semid, SEM_SIZE, SETALL, values); if(-1 == ret) { perror("semctl():"); exit(EXIT_FAILURE); } FILE *fp = fopen(argv[1], "a+"); if(NULL == fp) { perror("fopen():"); exit(EXIT_FAILURE); } int pid = fork(); if(pid == -1) { perror("fork():"); exit(EXIT_FAILURE); } else if(pid == 0) { struct sembuf wait_p = { .sem_num = 0, .sem_op = -1, .sem_flg = 0 }; struct sembuf signal_p = { .sem_num = 1, .sem_op = +1, .sem_flg = 0 }; for(int i = 0; i < 10; i++) { semop(semid, &wait_p, 1); time_t curtime; time(&curtime); struct tm *tm_now = localtime(&curtime); char buf[40] = ""; strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", tm_now); fwrite(buf, 1, strlen(buf), fp); fflush(fp); semop(semid, &signal_p, 1); } fclose(fp); exit(0); } else if(pid > 0) { struct sembuf wait_c = { .sem_num = 1, .sem_op = -1, .sem_flg = 0 }; struct sembuf signal_c = { .sem_num = 0, .sem_op = +1, .sem_flg = 0 }; for(int i = 1; i