您的位置:首页 > 运维架构 > Linux

[Linux管道和IPC]在父子进程中使用管道

2017-11-18 19:06 253 查看
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <stdlib.h>
#include <errno.h>

int main(int argc,char *argv[])
{
int n, fd[2];
pid_t pid;
char buffer[25];  //缓冲区
if(pipe(fd)<0)    //创建一个管道,两个文件描述符在fd数组中
{
printf("创建管道失败!\n ");
exit(0);
}
if((pid=fork())<0)    //创建一个子进程
{
printf("创建子进程失败!\n ");
exit(0);
}
else if (pid>0)   //父进程
{
close(fd[0]);
write(fd[1],"This is a pipe test!\n",22);  //向管道写入数据,注意回车换行符
}
else  //子进程
{
close(fd[1]); //关闭
n = read(fd[0],buffer,25);  //从通道中读出数据
printf("%s",buffer);  //将数据写到标准输出设备
}
exit(0);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Linux管道