#include<stdio.h>
#include<stdlib.h>
main()
{ int x,fd[2];
char buf[30],s[30];
pipe(fd);
while((x=fork())==-1);
if(x==0)
{
sprintf(buf,"this is an example\n");
printf("child procee running! \n");
write(fd[1],buf,30); /*把buf中的字符写入管道*/
sleep(5); /*睡眠5秒,让父进程读*/
exit(0); /*关闭x,子进程自我中止*/
}
else
{
wait(0); /*父进程挂起直到其某一子进程中止为止*/
read(fd[0],s,30);
printf("%s",s);
}
}
#include<stdio.h>
#include<stdlib.h>
main()
{
int x,y,i,fd[2];
char buf[30],s[30];
pipe(fd);
while((x=fork())==-1);
if(x==0)
{
lockf(fd[1],1,0);
sprintf(buf,"child1 is sending a message!\n");
printf("child1 process running! \n");
write(fd[1],buf,30); /*把buf中的字符写入管道*/
sleep(5); /*睡眠5秒,让父进程读*/
lockf(fd[1],0,0);
exit(0); /*关闭x,子进程自我中止*/
}
else
{
while((y=fork())==-1);
if(y==0)
{
lockf(fd[1],1,0);
sprintf(buf,"child2 is sending a message!\n");
printf("child2 process running! \n");
write(fd[1],buf,30); /*把buf中的字符写入管道*/
sleep(5); /*睡眠5秒,让父进程读*/
lockf(fd[1],0,0);
exit(0); /*关闭y,子进程自我中止*/
}
else
{
for(i=0; i<2; i++)
{
wait(0); /*父进程挂起直到其某一子进程中止为止*/
read(fd[0],s,30);
printf("%s",s);
}
}
}
}