Linux无名管道通信介绍

Linux下无名管道一般仅用于父子进程间的通信;

测试代码如下

//file name: fifo_test.c
#include <sys/prctl.h>
#include "fifo_test.h" int
main(int argc, char **argv)
{
int ret = 0;
char buf[32] = {'\0'};
int pipe_fd[2]; //0---read 1--write
pid_t pid; if(pipe(pipe_fd)<0)
{
printf("pipe create error/n");
return -1;
}
if((pid=fork())==0) //子进程
{
close(pipe_fd[0]);
prctl(PR_SET_NAME, "child");
while(1)
{
strcpy(buf, "hi, from child process!");
ret=write(pipe_fd[1],buf,sizeof(buf));
sleep(3);//
}
} close(pipe_fd[1]);
while(1)
{
ret=read(pipe_fd[0],buf,sizeof(buf));
printf("father process, recv msg: %s\n",buf);
} return 0;
}

编译

gcc -c fifo_test.c -o fifo_test.o -Wall -g
gcc fifo_test.o -o fifo_test -Wall -g

执行结果

./fifo_test
father process, recv msg: hi, from child process!, len: 32
father process, recv msg: hi, from child process!, len: 32
father process, recv msg: hi, from child process!, len: 32
上一篇:Namespace, string, vector and array


下一篇:linux中用无名管道进行文件的读写