【发布时间】:2014-02-26 02:32:32
【问题描述】:
我有一个从命令行参数运行程序的主程序。命令行程序被分叉并在子进程中运行。当发送 SIGINT 时,我想抓住它并要求用户确认他/她要退出。如果是,则父母和孩子都结束,否则孩子继续运行。 我的问题是,当用户拒绝时,我无法让孩子重新开始跑步。 我试过 SIGSTOP & SIGCONT 但这些实际上只是导致进程停止。
#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);
}
}
【问题讨论】:
-
我认为你也可以在子进程中使用
signal(SIGINT, SIG_IGN);,或者为它编写另一个SIGINT处理程序。 -
否,如果我阻止 sigint,那么当用户按下 ctrl C 时,无限子进程永远不会停止。我想发送 cntl C sig 并要求用户确认他是否真的想退出,如果用户说不,然后子进程继续
-
您可以阻止子进程退出父进程。你有一个孩子的pid。 SIGINT 来到父进程和子进程。父进程调用您的处理程序。 Child 默认处理这个信号。这是你的问题。
标签: c signals systems-programming