您的位置:首页 > 其它

无名管道(pipe)使用实例

2012-11-04 16:14 441 查看
无名管道(pipe)的创建实例,一下程序在子进程中写入数据,在父进程中读取数据

View Code

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main()
{
pid_t pid;
int pipedes[2];
char s[14] = "test message!";
char d[14] = {0};

if(pipe(pipedes) == -1)//创建管道
{
perror("pipe");
exit(1);
}

if((pid = fork()) == -1)//创建新进程
{
perror("fork");
exit(1);
}
else if(pid == 0)//子进程
{
printf("write data to the pipe\n");
if(write(pipedes[1], s, 14) == -1)//写数据到管道
{
perror("write");
exit(1);
}
else
{
printf("the written data is %s\n", s);
}
}
else if(pid > 0)//父进程
{
sleep(2);//休眠2秒钟,让子进程先运行
printf("read data from the pipe\n");
if(read(pipedes[0], d, 14) == -1)//读取管道数据
{
perror("read");
exit(1);
}
printf("data from pipe is %s\n", d);
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: