Linux无名管道通信

要求:

由父进程创建一个管道,然后再创建2个子进程,并由这两个兄弟进程利用管道进行进程通信:子进程1使用管道的写端,子进程2使用管道的读端。通信的具体内容可根据自己

的需要随意设计。

代码如下:

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define BUFNUM 60
int main(void)
{
	int n;
	int fd[2];//存放读端和写端的文件描述符
	pid_t pid1 = -1,pid2 = -1;
	char buf[BUFNUM];
	pipe(fd);//创建匿名管道
	pid1 = fork();//在父进程中创建子进程1
	
	if(pid1 != 0) {//确保是在父进程中创建子进程2,而不是在子进程1中创建
		pid2 = fork();//在父进程中创建子进程2
	}

	//fork()返回值: 若成功调用一次则返回两个值,子进程返回0,父进程返回子进程ID;否则,出错返回-1
	if (pid1 == 0)   /* child1 */
	{
		close(fd[0]);//关闭读端
		char child1_write[7] = "hello!";
		printf("child1 is writing,child2 is blocked.\n");
		printf("child1 say:I write %s\n",child1_write);
		write(fd[1], child1_write, 7);
	}
	if(pid2 == 0)           /* child2 */
	{
		close(fd[1]);//关闭写端
		n = read(fd[0], buf, 7);
		printf("child2 say:I awake.");
		printf("child2 say:I read %s\n",buf);
		printf("child2 say:I read %d byte",n);
	}
	return 0;
}


版权声明:本文为u014285517原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。