我要测试两个进程之间的信号量,为什么父进程没有在sem_wait(&s2
之后输入代码,请注意我已经在子进程中使用sem_post(&s2)
发出了s2信号。
include <linux/unistd.h>
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <math.h>
#include <semaphore.h>
sem_t s1,s2;
int value;
int main(){
sem_init(&s1,1,1);
sem_init(&s2,1,0);
pid_t childpid;
int generate[100];
if((childpid = fork()) == -1)
{
perror("fork");
exit(1);
}
if(childpid == 0)
{
while(1)
{
printf("im child befor enter critical section\n");
sem_wait(&s1);
printf("im child inside crtical section\n");
generate[0]=1;
generate[1]=2;
sem_getvalue(&s2,&value);
printf("value of s2 befor post is %d\n",value);
sem_post(&s2);
sem_getvalue(&s2,&value);
printf("im child exiting after post parent,the value after post s2 is %d \n",value);
}
}
else
{
while(1)
{
printf("im parent befor enter critical section\n");
sem_wait(&s2);
printf("im parent inside critical section\n");
printf("Received integer: %d\n", generate[0]);
printf("Received integer: %d\n", generate[1]);
sem_post(&s1);
printf("im parent exit after post child \n");
}
}
return(0);
}
这是输出:
im parent befor enter critical section
im child befor enter critical section
im child inside crtical section
value of s2 befor post is 0
im child exiting after post parent,the value after post s2 is 1
im child befor enter critical section