5.11作业

创建AB进程,要求如下:
a.A进程先发送一句话给B进程,B进程接收到后打印到终端上;
b.在a要求之后,B进程发送一句话给A进程,A进程接收后打印。
c.重复a, b步骤,直到发送或者接收到quit后,结束AB进程。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#include <signal.h>
int main()
{
    int a_to_b[2], b_to_a[2];
	pid_t pid;
    char buf[256]="";


    if (pipe(a_to_b) < 0 || pipe(b_to_a) < 0)
    {
        fprintf(stderr, "pipe failed\n");
        return -1;
    }

    if ((pid = fork()) < 0)
	{
		fprintf(stderr, "fork failed\n");
		return -1;
	}
	else if (pid > 0) // parent process A
	{ 
		close(a_to_b[0]); // 关闭管道读端
		close(b_to_a[1]); // 关闭管道写端

		while(1)
		{
			// 发送消息给B
			printf("Send message from A to B (type 'quit' to exit): ");
			scanf("%s",buf);
			write(a_to_b[1],buf, strlen(buf) + 1);
			// 如果输入“quit”消息,则退出循环                        
			if (strcmp(buf, "quit") == 0)
			{
				break;
			}
			// 接收来自B的消息并打印
			bzero(buf,sizeof(buf));
			read(b_to_a[0], buf, sizeof(buf));
			// 如果接收到“quit”消息,则退出循环                        
			if (strcmp(buf, "quit") == 0)
			{
				break;
			}
			printf("Received from B: %s\n", buf);
		}
		close(a_to_b[1]);
		close(b_to_a[0]);
		kill(pid, SIGKILL);  // 强制杀死子进程
		waitpid(-1,NULL,0);
		exit(0);
	}
	else // child process B
	{ 
		close(a_to_b[1]); // 关闭管道写端
		close(b_to_a[0]); // 关闭管道读端
		while(1)
		{
			// 接收来自A的消息并打印
			bzero(buf,sizeof(buf));
			read(a_to_b[0], buf, sizeof(buf));
			// 如果接收到“quit”消息,则退出循环                        
			if (strcmp(buf, "quit") == 0)
			{
				break;
			}
			printf("Received from A: %s\n", buf);
			// 发送消息给A
			printf("Send message from B to A (type 'quit' to exit): ");
			scanf("%s",buf);
			write(b_to_a[1], buf, strlen(buf) + 1);
			// 如果接收到“quit”消息,则退出循环
			if (strcmp(buf, "quit") == 0)
			{
				break;
			}
		}                                                              
		close(a_to_b[0]);
		close(b_to_a[1]);
		exit(0);

	}

	return 0;
} 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值