ubuntu环境下的PV原语中的互斥
程序代码:
#include <stdio.h> #include <sys/sem.h> #include <unistd.h> int p(int semid) { struct sembuf sops; sops.sem_op = -1; sops.sem_num = 0; sops.sem_flg = SEM_UNDO; semop(semid, &sops, 1); return 0; } int v(int semid) { struct sembuf sops; sops.sem_op = +1; sops.sem_num = 0; sops.sem_flg = SEM_UNDO; semop(semid, &sops, 1); return 0; } int sem_init(int semid, int val) { int ret; ret = semctl(semid, 0, SETVAL, val); return 0; } int mutual_exclusive() { int ret; int semid; pid_t pid; semid = semget(IPC_PRIVATE, 1, IPC_CREAT); if (semid < 0) { perror("semget"); return -1; } ret = sem_init(semid, 1); if (ret < 0) { perror("semctl"); return -1; } printf("%d\n", semctl(semid, 0, GETVAL)); pid = fork(); if (pid < 0) { perror("fork"); return -1; } if (pid == 0) { while(1) { p(semid); printf("this is child1\n"); printf("this is child2\n"); printf("this is child3\n"); v(semid); } } else { while(1) { p(semid); printf("this is parent1\n"); printf("this is parent2\n"); printf("this is parent3\n"); v(semid); } } return 0; } int main() { mutual_exclusive(); return 0; }
我想要的结果是输出child和parent是3个为一组的输出,但是结果是交叉输出的,没看出问题所在,求指教,谢了