本次程序实现了通过信号量来实现父进程与子进程互斥操作,当父进程执行打印操作时子进程被阻塞,当子进程执行打印操作时父进程阻塞。实现代码如下:
#include
#include
#include
#include
#include
#include
#include
#include
int semId;
int SIZE = 1;
union semun {
int val; /* Value for SETVAL */
struct semid_ds *buf; /* Buffer for IPC_STAT, IPC_SET */
unsigned short *array; /* Array for GETALL, SETALL */
struct seminfo *__buf; /* Buffer for IPC_INFO
(Linux-specific) */
};
void Handle(int s){
if(s == 2){
semctl(semId,0,IPC_RMID);
exit(0);
}
}
int main(){
signal(2,Handle);
key_t key = ftok(".",4);
semId = semget(key,1,IPC_CREAT | IPC_EXCL | 0666);
union semun val;
val.val = SIZE;
if(semctl(semId,0,SETVAL,val) == -1){
printf("semctl error!
");
exit(0);
}
struct sembuf p;
p.sem_num = 0;
p.sem_op = -1;
p.sem_flg = 0;
struct sembuf v = {0,1,0};
if(fork() > 0){
while(1){
semop(semId,&p,1);
printf("father go go go!!!
");
sleep(1);
printf("father go go go!!!
");
sleep(1);
printf("father go go go!!!
");
semop(semId,&v,1);
}
}
else{
while(1){
semop(semId,&p,1);
printf("child go go go!!!
");
sleep(1);
printf("child go go go!!!
");
sleep(1);
printf("child go go go!!!
");
semop(semId,&v,1);
}
}
return 0;
}
实现结果如下: