【问题标题】:waitpid() not allowing SIGINT to be sent to child process?waitpid() 不允许将 SIGINT 发送到子进程?
【发布时间】: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 的部分)

感谢您的帮助。

【问题讨论】:

    标签: c unix


    【解决方案1】:

    问题在于子进程获得了相同的 SIGINT 覆盖处理程序。您可能希望在 fork 之后重置子进程中的信号处理程序,或者您可能希望在已经 fork 子进程后在父进程中安装信号处理程序,因此它不会继承覆盖的处理程序。

    【讨论】:

    • 这是真的吗?我认为execve() 重置了子进程中未忽略信号的信号配置。
    猜你喜欢
    • 1970-01-01
    • 2017-10-02
    • 2010-11-08
    • 1970-01-01
    • 2010-12-03
    • 1970-01-01
    • 2018-11-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多