20240813 作业

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <wait.h>
#include <signal.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/un.h>

typedef struct sockaddr_in addr_in_t;
typedef struct sockaddr addr_t;
typedef struct sockaddr_un addr_un_t;

void handler(int signum)
{
	if(signum == SIGINT)
	{
		int rbfd = open("b_pid.txt", O_RDONLY);
		int b_pid = 0;
		read(rbfd, &b_pid, 4);
		printf("b_pid = %d\n", b_pid);
		kill(b_pid, SIGINT);
		printf("a向b发送信号成功!准备退出\n");
		close(rbfd);
		exit(0);
	}
	else if(signum == SIGTSTP)
	{
		while(waitpid(-1, 0, WNOHANG) != -1);
		printf("A收到B的SIGTSTP信号,准备回收a进程资源,A进程结束\n");
		sleep(1);
		exit(0);
	}
}

int main(int argc, const char *argv[])
{
	pid_t pid = fork();
	if (pid > 0)
	{ // A 进程接受到B进程的SIGTSTP信号后,会后a进程的资源后也结束运行
		signal(SIGINT, SIG_IGN);//忽视
		int wafd = open("a_pid.txt", O_WRONLY | O_TRUNC | O_CREAT, 0666);
		int A_pid = getpid();
		write(wafd, &A_pid, 4);
		close(wafd);
		signal(SIGTSTP, handler);
	}
	else if (pid == 0)
	{ // a 按ctrl+c结束a进程的运行,a进程结束运行之前,通过kill函数向b进程发送SIGINT信号
		signal(SIGINT, handler);//进入handler
		sleep(1);
	}
	while(1);
	return 0;
}
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
#include <semaphore.h>
#include <wait.h>
#include <signal.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/msg.h>
#include <sys/shm.h>
#include <sys/un.h>

typedef struct sockaddr_in addr_in_t;
typedef struct sockaddr addr_t;
typedef struct sockaddr_un addr_un_t;

void handler(int signum)
{
	if (signum == SIGINT)
	{
		printf("b接受到SIGINT信号,准备退出\n");
		sleep(1);
		exit(0);
	}
	if (signum == SIGCHLD)
	{
		while(waitpid(-1, 0, WNOHANG) != -1);
		printf("回收b资源成功\n");

		int rAfd = open("a_pid.txt", O_RDONLY);
		int A_pid = 0;
		read(rAfd, &A_pid, 4);
		printf("A_pid = %d\n", A_pid);
		kill(A_pid, SIGTSTP);
		printf("B向A发送SIGTSTP信号成功,准备退出\n");
		close(rAfd);
		sleep(1);
		exit(0);
	}
}

int main(int argc, const char *argv[])
{
	pid_t pid = fork();
	if (pid > 0)
	{ // B进程回收b进程的资源后,大B进程再使用kill函数向A进程发送SIGTSTP信号后
		// 大B进程结束运行
		signal(SIGCHLD, handler);
	}
	else if (pid == 0)
	{ // b进程死亡后
		int b_pid = 0;
		b_pid = getpid();
		printf("b_pid = %d\n", b_pid);
		int rbfd = open("b_pid.txt", O_WRONLY | O_TRUNC | O_CREAT, 0666);
		write(rbfd, &b_pid, 4);
		close(rbfd);
		signal(SIGINT, handler);
	}
	while (1);
	return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值