我一直在試圖弄清楚,如果這是可能的方式,我已經做到了。這個程序應該分叉一個循環打印到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