利用signal实现子进程结束时向父进程发送通知消息的功能,c语言程序实现
时间: 2024-05-08 20:17:11 浏览: 139
利用信号进行进程间通信
4星 · 用户满意度95%
以下是使用signal实现子进程结束时向父进程发送通知消息的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
void handler(int signum) {
printf("Child process has terminated.\n");
}
int main() {
pid_t pid;
int status;
signal(SIGCHLD, handler); // 注册信号处理函数
pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
} else if (pid == 0) {
// 子进程
printf("Child process is running.\n");
sleep(3);
printf("Child process is exiting.\n");
exit(EXIT_SUCCESS);
} else {
// 父进程
printf("Parent process is waiting for child process.\n");
wait(&status); // 等待子进程结束
printf("Parent process has received child process status.\n");
}
return 0;
}
```
在上面的代码中,我们使用signal函数注册了一个信号处理函数handler,用于处理子进程结束时发送给父进程的SIGCHLD信号。当子进程退出时,会向父进程发送SIGCHLD信号,父进程收到信号后会调用handler函数输出一条消息。
运行上面的程序,我们可以看到如下输出:
```
Parent process is waiting for child process.
Child process is running.
Child process is exiting.
Child process has terminated.
Parent process has received child process status.
```
可以看到,当子进程结束时,父进程收到了通知并输出了消息。
阅读全文