您的位置:首页 > 编程语言

UNIX环境高级编程学习之第十五章进程间通信 - 通过半双工匿名管道实现父子进程通信

2010-08-18 11:39 981 查看
UNIX环境高级编程学习之第十五章进程间通信 - 父子进程通过半双工匿名管道通信

/* User:Lixiujie
* Date:20100818
* Desc:父子进程通过半双工匿名管道通信
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>

int main(void){
pid_t pid;
int pfd[2];
int cfd[2];
char szBuf[256];
if (pipe(pfd) < 0){
perror("pipe(pfd) failed!");
exit(1);
}
if (pipe(cfd) < 0){
perror("pipe(cfd) failed!");
exit(1);
}
if ((pid = fork()) < 0){
perror("fork() failed!");
exit(1);
}else if (pid > 0){ // parent
close(cfd[0]); // colse child read
close(pfd[1]); // colse parent write
while (1){
memset(szBuf, 0x00, sizeof(szBuf));
strcpy(szBuf, "P: Hello world!");
write(cfd[1], szBuf, strlen(szBuf)+1);
memset(szBuf, 0x00, sizeof(szBuf));
read(pfd[0], szBuf, sizeof(szBuf) - 1);
printf("%s/n", szBuf);
sleep(1);
}
}else{ // child
close(cfd[1]);
close(pfd[0]);
while (1){
memset(szBuf, 0x00, sizeof(szBuf));
read(cfd[0], szBuf, sizeof(szBuf) - 1);
printf("%s/n", szBuf);
memset(szBuf, 0x00, sizeof(szBuf));
strcpy(szBuf, "C: Hello world!");
write(pfd[1], szBuf, strlen(szBuf)+1);
sleep(1);
}
}
return 0;
}


注意:当最后一个访问管道进程终止时,管道就被完全地删除了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐