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