风声笔记

微信订阅号:fensnote 技术点滴,积少成多,水滴石穿,水到渠成……

导航

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

 

posted on 2020-03-24 08:18  风声笔记  阅读(178)  评论(0编辑  收藏  举报