华清远见上海中心22071班

创建AB进程,要求用B进程杀死A进程

A进程代码

#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
	if(mkfifo("./fifo", 0777)<0)
	{
		if(17 != errno)
		{
			perror("mkfifo");
			return -1;
		}
		printf("创建成功\n");
	}
	int pf=open("./fifo", O_WRONLY);
	if(pf<0)
	{
		perror("open");
		return -1;
	}
	pid_t pid=getpid();
	write(pf,&pid, sizeof(pid));
	printf("写入成功\n");
	while(1)
	{
		printf("只是A进程\n");
		sleep(1);
	}

	close(pf);

	
	
	return 0;
}

B进程代码

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<signal.h>
#include <unistd.h>
#include <errno.h>
int main(int argc, const char *argv[])
{
	printf("这是B进程\n");
	if(mkfifo("./fifo", 0777)<0)
	{
		if(17 != errno)
		{
			perror("mkfifo");
			return -1;
		}
		printf("创建成功\n");
	}
	int mp=open("./fifo", O_RDONLY);
	if(mp<0)
	{
		perror("open");
		return -1;
	}
	pid_t pid;
	char c;
	read(mp,&pid, sizeof(pid));
	printf("读取成功\n");
	printf("请输入是否杀死A进程Y/N: ");
	scanf("%c", &c);
	getchar();
	
	kill(pid, 9);

	close(mp);

	
	
	return 0;
}

要求实现AB进程对话:
1)A进程发送一句话,B进程接收后打印;
2)B进程接着再发送一句话,A进程接收打印;
3)重复上述步骤,当A进程或者B进程接收到quit后退出AB进程。

AJ进程

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include<fcntl.h>
#include <unistd.h>
#include <string.h>
int main(int argc, const char *argv[])
{
	int res;
	if(mkfifo("./fifo", 0777)<0);
	{
		if(17!=errno)
		{
			perror("mkfifo");
			return -1;
		}
	}
	printf("创建成功\n");
	int p;
	p=open("./fifo", O_WRONLY);
	if(p<0)
	{
		perror("open");
		return -1;
	}
	char str[128]="";
	ssize_t s;
	while(1)
	{
		printf("请输入》》");
		fgets(str, sizeof(str), stdin);
		str[strlen(str)-1]='\0';
		s=write(p, str, sizeof(str));
		if(s<0)
		{
			perror("write");
			return -1;
		}
		printf("输入成功\n");
		if(strcmp(str,"quit")==0)
		{
			break;
		}
	}
	close(p);



	
	return 0;
}

B进程

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include<fcntl.h>
#include <unistd.h>
#include <string.h>
int main(int argc, const char *argv[])
{
	int res;
	if(mkfifo("./fifo", 0777)<0);
	{
		if(17!=errno)
		{
			perror("mkfifo");
			return -1;
		}
	}
	printf("创建成功\n");
	int p;
	p=open("./fifo", O_RDONLY);
	if(p<0)
	{
		perror("open");
		return -1;
	}
	char str[128]="";
	ssize_t s;
	while(1)
	{
		s=read(p, str, sizeof(str));
		if(s<0)
		{
			perror("read");
			return -1;
		}
		else if(0==s)
		{
			break;
		}
		printf("%s\n", str);
	}
	close(p);
		



	
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值