|
假设数据是由父写子读,那么父进程关闭匿名管道的读端,子进程关闭匿名管道的写端,但如果我不关闭,严格的控制数据流向的时间,双向通讯没有报错,如果不控制时序,父进程自写自读快于子进程,子进程成僵尸进程,我是linux编,请给位大佬指点一下。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#include <sys/wait.h>
int main(){
int fd[2];
pid_t pid;
int ret=pipe(fd);
if(ret==-1){
perror("pipe error");
exit(1);
}
pid=fork();
if(pid==-1){
perror("fork error");
exit(1);
}
else if(pid==0)
{
//close(fd[1]);
char buf[1024];
ret=read(fd[0],buf,128);
printf("son read %d byte from father,%s\n",ret,buf);
sleep(5);
ret=write(fd[1],"hello,father",sizeof("hello,father"));
printf("son write %d byte to father\n",ret);
}else{
//close(fd[0]);
char buf1[128];
sleep(5);
ret=write(fd[1],"hello,son\n",sizeof("hello,son\n"));
printf("father write %d byte\n",ret);
sleep(3);
ret=read(fd[0],buf1,128);
printf("i receive %dbyte from son,is %s\n",ret,buf1);
}
return 0;
}
运行结果:
father write 11 byte
son read 11 byte from father,hello,son
son write 13 byte to father
i receive 13byte from son,is hello,father
|
上一篇: 匿名管道不知道为什么可以双向通信,请各位大佬指正下一篇: 用MFC自绘窗口遇到的小问题
|