1
#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <limits.h>
#include <unistd.h>
#include <stdlib.h>
#include <pwd.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
void sig_handler(int signal);
int pid, forkFlag = 0;
int main(int argc, char **argv, char **envp)
{
sigset(SIGINT, sig_handler); //handle ctrl + c
sigignore(SIGTSTP);
sigignore(SIGSTOP);
int ex, rv, status;
forkFlag = 1; //fork is being called
pid = fork();
if(pid == -1){
perror("fork");
exit(2);
}
else if (pid == 0){ //if child process
ex = access(argv[0], X_OK); //check if file is executable
if(ex){
perror("access");
exit(1);
}
else{
rv = execve(argv[0], argv, envp); //run program in child process
if(rv == -1){
perror("execve");
exit(1);
}
}
exit(0); //end child process
}
else{
rv = waitpid(pid, &status, 0); //wait for child
if(rv == -1){
perror("waitpid");
}
if(WEXITSTATUS(status)){ //check status of child if it did ot return 0
printf("The return status of the child was %d\n", WEXITSTATUS(status));
}
}
forkFlag=0;
}
void sig_handler(int signal)
{
if(signal == SIGINT && (pid && forkFlag)){
kill(pid,signal); //send kill to child
}
}
我想让我的程序忽略ctrl + C,除非有一个子进程在运行,那么它会将SIGINT发送到子进程。但是,当子进程正在运行时,按ctrl + c时,waitpid()返回-1,并显示错误“Interrupted System Call”。这使得子进程停止运行,但是如果我使用ps,那么子进程仍然存在,但现在标记为“已停用”。我从printf语句知道kill是函数sig_handler的函数,而pid和forkFlag是它们的正确值。 waitpid()让我的程序忽略杀手?我该如何解决?我知道这个代码几乎没有,但它是我的代码的一小部分(唯一涉及叉的部分)waitpid()不允许将SIGINT发送给子进程?
感谢您的任何帮助。
这是真的吗?我认为'execve()'重置了子进程中未忽略信号的信号处置。 – 2013-12-05 04:32:28