Linux手册中对匿名管道的描述如下:
DESCRIPTION
pipe() creates a pipe, a unidirectional data channel that can be used for interprocess communication. The array pipefd is used to return two file descriptors referring to the ends of the pipe. pipefd[0] refers to the read end of the pipe. pipefd[1] refers to the write end of the pipe. Data written to the write end of the pipe is buffered by the kernel until it is read from the read end of the pipe. For further details, see pipe(7).
调用pipe()
接口后会创建一个匿名管道并返回管道读写两端的描述符,其中pipefd[0]
为读端,pipefd[1]
为写端。通常用于父子进程间的通信。
对于pipe()
返回的描述符可以直接进行read/write
操作,无需调用open()
。
测试代码如下。
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#define BUFFSIZE 128
int main(int argc, char* argv[])
{
int pipefd[2] = {0, 0};
pid_t pid = -1;
unsigned char buff[BUFFSIZE] = {0};
int count = 0;
if(0 != pipe(pipefd))
{
perror("create pipe failed!");
return -1;
}
pid = fork();
if(-1 == pid)
{
perror("fork error");
return -1;
}
if(pid == 0)/* child process */
{
close(pipefd[1]);
while(1)
{
memset(buff, 0, BUFFSIZE);
if(0 < read(pipefd[0], buff, sizeof(buff)))
{
printf("[child rec]:%s\n", buff);
}
sleep(5);
}
}
else /* parent process */
{
close(pipefd[0]);
while(1)
{
memset(buff, 0, sizeof(buff));
sprintf(buff, "Hello-%d", ++count);
if(-1 != write(pipefd[1], buff, BUFFSIZE))
{
printf("[parent send]:%s\n", buff);
}
sleep(1);
}
}
return 0;
}
标签:pipe,read,pid,pipefd,管道,间通信,匿名,include,buff
From: https://www.cnblogs.com/lucky-glc/p/16643530.html