非父子进程间通信信号,代码
时间: 2023-12-20 16:51:01 浏览: 32
下面是一个使用信号进行非父子进程间通信的示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
void handler(int sig) {
printf("Received signal %d\n", sig);
}
int main() {
pid_t pid1, pid2;
// 创建子进程1
pid1 = fork();
if (pid1 == 0) {
// 子进程1
printf("Child 1 (pid=%d) is running\n", getpid());
sleep(5);
// 向父进程发送信号
kill(getppid(), SIGUSR1);
exit(0);
} else {
// 创建子进程2
pid2 = fork();
if (pid2 == 0) {
// 子进程2
printf("Child 2 (pid=%d) is running\n", getpid());
sleep(10);
// 向父进程发送信号
kill(getppid(), SIGUSR2);
exit(0);
} else {
// 父进程
printf("Parent (pid=%d) is running\n", getpid());
// 注册信号处理函数
signal(SIGUSR1, handler);
signal(SIGUSR2, handler);
// 等待信号
int count = 0;
while (count < 2) {
sleep(1);
count++;
}
printf("Parent exiting\n");
exit(0);
}
}
return 0;
}
```
该程序创建了两个子进程,分别运行5秒和10秒,然后向父进程发送信号SIGUSR1和SIGUSR2。父进程注册了信号处理函数handler,等待接收两个信号后退出。注意,这里使用了两个不同的信号来区分不同的子进程发送的信号。