![](https://i-blog.csdnimg.cn/direct/0b450b63f0bf4c15b454b52a11240e49.png)
#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;
}
![](https://i-blog.csdnimg.cn/direct/323aea2e3e2c4cceae65d62fd847ab19.jpeg)