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

linux 进程编程:无名管道pipe

2015-05-24 22:36 495 查看
今天写一下利用无名管道pipe进行进程间通信。

该通信方法利用两个文件描述符进行通信,其中pipes[0] 用于读, pipes[1]用于写。

相关函数

#include <unistd.h>

pid_t fork(void);

int pipe(int file_descriptor[2]);

测试代码

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

int main(int argc, char **argv)
{
int ret = -1;
unsigned char test_buf[16] = {0};
pid_t pid;
int pipes[2];

ret = pipe(pipes);
if(0 != ret)
{
printf("[%s:%d]pipe fail\n", __func__, __LINE__);
}
else
{
pid = fork();
if(pid < 0)
{
printf("[%s:%d] fork fail\n", __func__, __LINE__);
}
else if(0 == pid)
{
ret = read(pipes[0], test_buf, sizeof(test_buf));
if(ret > 0)
{
printf("[%s:%d] read data:%s\n", __func__, __LINE__, test_buf);
}
}
else
{
ret = write(pipes[1], "hello pipe!", 11);
if(ret <= 0)
{
printf("[%s:%d] write data fail\n", __func__, __LINE__);
}
}
}

return 0;
}
运行结果

[main:28] read data:hello pipe!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: