编写一个关于进程管道通信的简单程序,子进程送一串消息给父进程,父进程收到消息后把它显示出来。
要求:两个子进程分别向管道写一句话:
Child process 1 is sending a message!
Child process 2 is sending a message!
而父进程则从管道中读出来自两个子进程的信息,显示在屏幕上,且父进程要先接收子进程1发来的消息,然后再接收子进程2发来的消息.
#include<unistd.h>#include<stdio.h>#include<stdlib.h>int main()
{
int pid1,pid2;
int fd[2];
char buffer[100];
char inpipe1[]="Child process 1 is sending a massage!\n";
char inpipe2[]="Child process 2 is sending a massage!\n";
while(pipe(fd)==-1);
while((pid1=fork())==-1);//创建第一个子进程if(pid1==0)
{
lockf(fd[1],1,0);
sleep(2);
write(fd[1],inpipe1,50);//向管道内写入第一个子进程的标志
lockf(fd[1],0,0);
//exit(0);
}
else
{
while((pid2=fork())==-1);//创建第二个子进程if(pid2==0)
{
lockf(fd[1],1,0);
sleep(2);
write(fd[1],inpipe2,50);//向管道内写入第二个子进程的标志
lockf(fd[1],0,0);
//exit(0);
}
else
{
wait(0);
read(fd[0],buffer,50);//读出第一个子进程的标志printf("%s",buffer);
wait(0);//等待动作完成
read(fd[0],buffer,50);//读出第二个子进程的标志printf("%s\n",buffer);
exit(0);
}
}
return0;
}