1. 程式人生 > >Linux下父程序與兩子程序管道通訊

Linux下父程序與兩子程序管道通訊

#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
int main()
{int fd[2];
pid_t pid1,pid2;
char sendbuf[50],revbuf[50];
pipe(fd);
pid1=fork();
if(pid1==0)
{lockf(fd[1],1,0);
sprintf(sendbuf,"child1 is sending the message");
write(fd[1],sendbuf,50);
lockf(fd[1],0,0);
}
else
{
pid2=fork();
if(pid2==0)
{lockf(fd[1],1,0);
sprintf(sendbuf,"child2 is sending the message");
write(fd[1],sendbuf,50);
lockf(fd[1],0,0);
}
else{
wait(0);
read(fd[0],revbuf,50);
printf("%s\n",revbuf);
wait(0);
read(fd[0],revbuf,50);
printf("%s\n",revbuf);
}
}

return 0;
}