国庆作业day4

完成父子进程的通信,
父进程发送一句话后,子进程接收打印
然后子进程发送一句话,父进程接收后打印
 

#include "head.h"
#define buf_size 256
 
int main(int argc, const char *argv[])
{
	int fd[2];
	pid_t pid;
	char buf[buf_size];
	char msg1[] = "Hello child";
	char msg2[] = "Hello Parent!";
 
	// 创建管道
	if (pipe(fd) == -1) 
	{
		perror("pipe");
		exit(EXIT_FAILURE);
	}
	while(1)
	{
		// 创建子进程
		pid = fork();
		if (-1 == pid) 
		{
			perror("fork");
			exit(EXIT_FAILURE);
		}
 
		if (0 == pid) 
		{
			// 子进程
			close(fd[1]); // 关闭写端
 
			// 接收父进程发送的消息
			read(fd[0], buf, buf_size);
			printf("Child recv: %s\n", buf);
			
 
			// 发送消息给父进程
			write(fd[1], msg2, strlen(msg2) + 1);
			printf("Child send: %s\n", msg2);
 
			close(fd[0]); // 关闭读端
 
		} 
		else if(0 < pid) 
		{
			// 父进程
			close(fd[0]); // 关闭读端
 
			// 发送消息给子进程
			write(fd[1], msg1, strlen(msg1) + 1);
			printf("Parent send: %s\n", msg1);
 
			// 等待子进程结束
			wait(NULL);
 
			// 接收子进程发送的消息
			read(fd[0], buf, buf_size);
			printf("Parent recv: %s\n", buf);
 
			close(fd[1]); // 关闭写端
		}
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值