信如何使用信号使一个子进程结束另一个也结束
时间: 2023-12-18 11:06:00 浏览: 40
在 Linux 中,可以使用信号机制来实现一个进程结束另一个进程的功能。具体步骤如下:
1. 父进程创建两个子进程,子进程 A 和子进程 B。
2. 子进程 A 执行需要长时间运行的任务,例如死循环。
3. 父进程向子进程 B 发送 SIGUSR1 信号。
4. 子进程 B 收到 SIGUSR1 信号后,向子进程 A 发送 SIGTERM 信号。
5. 子进程 A 收到 SIGTERM 信号后,终止自己的进程。
下面是一个示例程序,实现了上述功能:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
pid_t pidA, pidB;
void sig_handler(int signo)
{
if (signo == SIGUSR1) {
printf("Received SIGUSR1 signal, sending SIGTERM to process A\n");
kill(pidA, SIGTERM);
}
}
void processA()
{
while (1) {
// 长时间运行的任务
}
}
void processB()
{
sleep(5);
kill(getppid(), SIGUSR1);
}
int main()
{
signal(SIGUSR1, sig_handler);
pidA = fork();
if (pidA == 0) {
processA();
exit(0);
}
pidB = fork();
if (pidB == 0) {
processB();
exit(0);
}
wait(NULL);
wait(NULL);
printf("Both processes have ended.\n");
return 0;
}
```
在上述程序中,父进程创建了两个子进程,分别执行 processA() 和 processB() 函数。processA() 是一个死循环,模拟了需要长时间运行的任务。processB() 调用 sleep() 函数等待 5 秒钟后向父进程发送 SIGUSR1 信号。
父进程在收到 SIGUSR1 信号后,调用 sig_handler() 函数,向子进程 A 发送 SIGTERM 信号,终止其进程。子进程 B 在向父进程发送 SIGUSR1 信号后就退出了。
最后,父进程调用 wait() 函数等待两个子进程的结束,输出 "Both processes have ended."。