【发布时间】:2011-03-04 04:50:45
【问题描述】:
#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 并显示错误“系统调用中断”。这使得子进程停止运行,但是如果我使用 ps,子进程仍然存在,但现在标记为已失效。我从 printf 语句中知道 kill 在函数 sig_handler 中被调用,并且 pid 和 forkFlag 是它们的正确值。 waitpid() 是否让我的程序忽略了杀戮?我该如何解决?我知道这段代码几乎什么都没做,但它只是我代码的一小部分(唯一涉及 fork 的部分)
感谢您的帮助。
【问题讨论】: