我需要fork
两个子进程。人们可以接收到信号3,打印hello
并将信号4发送给另一个子进程;另一个可以接收信号4,打印world
并将信号3发送给第一个子进程。
要开始,父进程会在睡眠3秒后将信号3发送到第一个子进程。
然后3秒钟后,父进程将发送SIGKILL
杀死他们两个。
fork和信号:如何从父进程发送信号到特定子进程
我不知道如何发送信号到一个特定的子进程(我知道我们有一个功能kill
发送信号,但我不知道在这里使用它)。
这里是我的代码:
#include <stdio.h>
#include <signal.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
void func(int n)
{
printf("ping\n");
// how to send signal 4 to the second process?
}
void func2(int n)
{
printf("pong\n");
// how to send signal 3 to the first process?
}
int main()
{
pid_t pid;
int i;
for(i = 0; i < 2; i++)
{
pid = fork();
if(pid == 0)
{
if(i == 0)
{
signal(3, func);
}
else
{
signal(4, func2);
}
while(1);
}
else
{
if(i == 1)
{
sleep(3);
// how to send signal 3 to the first child process?
sleep(3);
// how to kill the two children?
}
}
}
return 0;
}
在信号上下文中调用'printf()'的未定义行为。 – EOF
http:// man7。org/linux/man-pages/man2/kill.2.html – alk
@EOF我应该怎么做? – Yves