我有一個主要從命令行參數運行程序。命令行程序分叉並在子進程中運行。當SIGINT發送時,我想抓住它並要求用戶確認他/她想要退出。如果是的話,父母和孩子都結束,否則孩子會繼續跑步。 我的問題是,我不能讓孩子開始跑回來,當用戶說不。 我試過SIGSTOP & SIGCONT,但這些實際上只是導致進程停止。如何捕獲SIGINT並在子進程中忽略它?
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
extern char **environ;
void sigint_handler(int sig);
void sigint_chldhandler(int sig);
int main(int argc, char** argv)
{
int pid;
signal(SIGINT,sigint_handler);
if((pid=fork())==0)
{
printf("%d\n",pid);
execve(argv[1],argv,environ);
}
int status;
waitpid(pid,&status,0);
}
void sigint_handler(int sig)
{
printf("Do you want to quit?Yes/No:\n");
char buf[4];
fgets(buf, sizeof(char)*4, stdin);
printf("child pid:%d\n",getpid());
printf("parent pid:%d\n",getppid());
if(strcmp(buf,"Yes")==0)
{
kill(-getpid(),SIGKILL);
printf("Exiting!\n");
exit(0);
}
}
http://stackoverflow.com/questions/6803395/child-process-receives-parents-sigint - 是嗎? – someuser
你也可以在子進程中使用'signal(SIGINT,SIG_IGN);',或者爲它寫另一個SIGINT處理程序。 – someuser
如果我阻止sigint,那麼當用戶按下ctrl C時,infite子進程永遠不會停止。我想發送cntl C sig並要求用戶確認他是否真的要退出,如果用戶說沒有,那麼子進程繼續 – user3213348