如何在子进程中更改信号处理程序?

时间:2019-03-30 10:29:39

标签: c signals child-process job-control

我正在编写一个带有作业控制的shell。主进程应忽略停止信号并处理SIGCHLD。 fork()之后的子进程应将信号设置为SIG_DFL。问题是我的子进程也忽略了信号。

在程序开始时,我将shell设置为前台并初始化信号

...
tcsetpgrp(shell_terminal, shell_pgid);
set_signals();

void    chld_handler(int signum)
{
    if (signum == SIGCHLD)
        check_and_wait();
    return ;
}

void    set_signals() {
    sigset_t set;
    struct sigaction act;

    sigfillset(&set);
    sigprocmask(SIG_SETMASK, &set, NULL);

    ft_memset(&act, 0, sizeof(act));

    sigfillset(&act.sa_mask);
    act.sa_handler = SIG_IGN;

    sigaction(SIGINT, &act, NULL);
    sigaction(SIGQUIT, &act, NULL);
    sigaction(SIGTSTP, &act, NULL);
    sigaction(SIGTERM, &act, NULL);
    sigaction(SIGTTIN, &act, NULL);
    sigaction(SIGTTOU, &act, NULL);

    act.sa_handler = chld_handler;

    sigaction(SIGCHLD, &act, NULL);

    sigemptyset(&set);
    sigprocmask(SIG_SETMASK, &set, NULL);
    return;
}

在子进程中的fork()之后:

/* set to foreground */
pid = getpid();
if (!job->pgid)
    job->pgid = pid;
setpgid(pid, job->pgid);
tcsetpgrp(shell_terminal, job->pgid);

/* set signals */
sigset_t set;
struct sigaction act;

sigfillset(&set);
sigprocmask(SIG_SETMASK, &set, NULL);

memset(&act, 0, sizeof(act));
sigfillset(&act.sa_mask);

act.sa_handler = SIG_DFL;

sigemptyset(&set);
sigprocmask(SIG_SETMASK, &set, NULL);

execve(...);

但是子进程会忽略信号

1 个答案:

答案 0 :(得分:1)

sigaction()不会通过引用存储sigaction对象。 将act.sa_handler更改为act.sa_handler = SIG_DFL之后,您需要重复执行这些sigaction()呼叫。

sigaction(SIGINT, &act, NULL);
sigaction(SIGQUIT, &act, NULL);
sigaction(SIGTSTP, &act, NULL);
sigaction(SIGTERM, &act, NULL);
sigaction(SIGTTIN, &act, NULL);
sigaction(SIGTTOU, &act, NULL);