我有一个主要从命令行参数运行程序。命令行程序分叉并在子进程中运行。当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