[英]How to change signal handler in child-process?
我正在編寫一個帶有作業控制的外殼。 主進程應該忽略停止信號並處理 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(...);
但是子進程忽略信號
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.