您的位置:首页 > 其它

一个简单的无名管道示例

2012-09-14 17:10 281 查看
Linux中,函数

int pipe(int fds[2]);

创建一个无名管道,产生了两个 文件描述符,存放在数组 fds 中,其中 fds[0] 表示读端,fds[1] 表示写端;成功返回0,失败返回-1;

示例:创建一个无名管道,fork一个子进程,父进程写,子进程读。

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
int main(void){
int fds[2];
if(pipe(fds)){
perror("pipe");
exit(1);
}
pid_t pid;
char buf[80];
if((pid = fork()) < 0){
perror("fork");
exit(1);
}
else if(pid > 0){
printf("in father progress\n");
char s[] = "Hello~message from father progress~";
write(fds[1], s, sizeof(s));
close(fds[0]);
close(fds[1]);
}
else{
printf("in children progress\n");
read(fds[0], buf, 80);
printf("%s\n", buf);
close(fds[0]);
close(fds[1]);
}
waitpid(pid, NULL, 0);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: