创建父子进程,实现父子进程的通话。

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
int main(int argc, const char *argv[])
{

	int pfd[2] = {0};
	int pfd1[2] = {0};
	if (pipe(pfd) < 0)
	{
		perror("pipe pfd");
		return -1;
	}
	if (pipe(pfd1) < 0)
	{
		perror("pipe pfd1");
		return -1;
	}
	pid_t pid = fork();
	if (pid > 0)
	{
		// pfd父进程写,pfd1父进程读。
		char buf[128] = "";
		char buf1[128] = "";
		while (1)
		{
			close(pfd[0]);
			close(pfd1[1]);
			bzero(buf, sizeof(buf));
			printf("父发给子:");
			fgets(buf, sizeof(buf), stdin);
			buf[strlen(buf) - 1] = '\0';

			if (write(pfd[1], buf, sizeof(buf)) < 0)
			{
				perror("write");
				return -1;
			}

			if(strcmp(buf,"quit")==0)
			{
				break;
			}  

			bzero(buf1, sizeof(buf1));
			if (read(pfd1[0], buf1, sizeof(buf1)) < 0)
			{
				perror("read");
				return -1;
			}

			if(strcmp(buf1,"quit")==0)
			{
				break;
			}    	
			printf("父接收到子:%s\n", buf1);
		}
			close(pfd1[0]);
			close(pfd[1]);
			wait(NULL);
			printf("父进程退出\n");
	}
	else if (0 == pid)
	{
		// pfd子进程写,pfd1子进程读。
		close(pfd[1]);
		close(pfd1[0]);
		char buf[128] = "";
		char buf1[128] = "";
		while (1)
		{

			bzero(buf, sizeof(buf));

			if (read(pfd[0], buf, sizeof(buf)) < 0)
			{
				perror("read");
				return -1;
			}
			if(strcmp(buf,"quit")==0)
			{
				break;
			} 
			printf("子接收到父:%s\n", buf);
			bzero(buf1, sizeof(buf1));
			printf("子发给父:");
			fgets(buf1, sizeof(buf1), stdin);
			buf1[strlen(buf1) - 1] = '\0';
			if (write(pfd1[1], buf1, sizeof(buf1)) < 0)
			{
				perror("write");
				return -1;
			}
			if(strcmp(buf1,"quit")==0)
			{
				break;
			}
		}
		close(pfd1[1]);
		close(pfd[0]);
		printf("子进程退出\n");
	}
	else
	{
		perror("fork");
		return -1;
	}
	return 0;
}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值