我一直在试图弄清楚,如果这是可能的方式,我已经做到了。这个程序应该分叉一个循环打印到STDOUT的子进程,父进程应该退出以返回终端提示符。然后,小孩应该等待SIGINT告诉它何时关机。但是我记得读到SIGINT只发送给前台进程,这就解释了为什么我遗弃的孩子不受CTRL + C的影响。有没有办法让被遗弃的孩子接收终端发送的信号,或者终端中的某些系统呼叫将其带到可以接收到SIGINT的前台?还是我的搜索无望?无法发送信号给子进程C
代码:
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/wait.h>
#include <sys/types.h>
/* signal handler for the child process */
void catchInt (int signum)
{
printf("\nMy sincerest apologies, master\n");
exit(0);
}
/* signal handler for the parent process */
void ignoreInt (int signum)
{
/* prevent any extra output from being printed */
fflush(stdout);
/* wait for child to apologize before replying */
wait(NULL);
printf("You're welcome\n");
exit(0);
}
/* signal handler for the child's alarm */
void catchAlarm (int signum)
{
printf("It's great to be alive\n");
/* reset the alarm */
signal(SIGALRM, catchAlarm);
alarm(3);
}
int main() {
pid_t pid;
/* fork process */
pid = fork();
if (pid < 0) /* error handler */
{
fprintf(stderr, "Fork Failed");
exit(-1);
}
/* child */
else if (pid == 0)
{
printf("It's great to be alive\n");
/* catch SIGINT and handle as the child should */
signal(SIGINT, catchInt);
/* catch SIGALRM being sent by alarm() */
signal(SIGALRM, catchAlarm);
/* set alarm for 3 seconds */
alarm(3);
for (;;)
{
printf("I have 42001 children and not one comes to visit\n");
usleep(500000);
}
}
/* parent */
else
{
/* exit to abandon child process in the background */
exit(0);
}
return(0);
}
这实际上完美的作品!我将不得不更加关注进程组。谢谢! – JKomusin 2010-09-23 04:34:02
@JKomusin:尽管这不是一个完全可靠的解决方案,但请参阅更新。 – caf 2010-09-23 04:45:15