#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <errno.h>
#include <fcntl.h>
#include <signal.h>
int room=0;
char ch;
int main(int argc,char argv[])
{
pid_t pid;
pid_t pids[2];
int j=0;
int i=0;
struct sembuf sem_b;
sem_b.sem_num=0;
sem_b.sem_flg=SEM_UNDO;
room=semget(IPC_PRIVATE,1,0666|IPC__CREAT);
semctl(room,0,SETVAL,1);
for(i=0;i<2;i++){
pid=fork();
if(pid0)
{
while(1)
{
printf("%d want to enter room–WAIT\n",i);
sem_b.sem_op=-1;
semop(room,&sem_b,1);
printf("%d is in room \n",i);
sleep(3);
sem_b.sem_op=1;
semop(room,&sem_b,1);
printf("%d is out of room —SIGNAL OK \n",i);
}
}
else {
pids[i]=pid;
}
}
do
{
ch =getchar();
if(ch’q’)
for(i=0;i<2;i++)
kill(pids[i],SIGTERM);
}
while(ch!=‘q’);
}
三个进程互斥
最新推荐文章于 2022-06-11 17:53:15 发布