c - SIGTSTP 和 SIGCHLD 之间的关系是什么

标签 c linux signals posix sigchld

我为每个进程都有两个处理程序(SIGTSTP、SIGCHLD),问题是当我使用 SIGTSTP 暂停进程时,SIGCHLD 的处理程序函数也会运行。我该怎么做才能防止这种情况发生。

信号处理程序:

void signalHandler(int signal) {
int pid, cstatus;
if (signal == SIGCHLD) {
    susp = 0;
    pid = waitpid(-1, &cstatus, WNOHANG);
    printf("[[child %d terminated]]\n", pid);
    DelPID(&JobsList, pid);
}
}

void ctrlZsignal(int signal){
    kill(Susp_Bg_Pid, SIGTSTP);
    susp = 0;
    printf("\nchild %d suspended\n", Susp_Bg_Pid);
}

Susp_Bg_Pid 用于保存暂停的进程ID。
susp 表示“粉碎”父进程的状态(是否挂起)。

最佳答案

使用 sigactionSA_NOCLDSTOP 设置 SIGCHLD 处理程序。

来自 sigaction (2)

SA_NOCLDSTOP - If signum is SIGCHLD, do not receive notification when child processes stop (i.e., when they receive one of SIGSTOP, SIGTSTP, SIGTTIN or SIGTTOU) or resume (i.e., they receive SIGCONT)(see wait(2)). This flag is only meaningful when establishing a handler for SIGCHLD.

更新

void signalHandler(int sig)
{
  //...
}

struct sigaction act;

act.sa_handler = signalHandler;
sigemptyset(&act.sa_mask);
act.sa_flags = SA_NOCLDSTOP;

if (sigaction(SIGCHLD, &act, 0) == -1)
{
  perror("sigaction");
  exit(1);
}

如果您不熟悉 sigaction,您应该阅读它,因为它有几个不同的选项和行为,这些选项和行为远远优于 signal,但代价是在你弄清楚如何使用它之前,先要了解它的复杂性和困惑。我对您似乎想做的事情进行了最低限度的猜测,但您需要尽早了解这一点。

关于c - SIGTSTP 和 SIGCHLD 之间的关系是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19883512/

相关文章:

linux - 用于重命名文件以确保破折号两边都有空格的 Bash 脚本

linux - Bash - 如何正确列出文件夹中的文件并管理排除

c++ - 在 C++ 中将 uint8_t 缓冲区转换为复杂的浮点缓冲区

c - 读取字而不是字节

c - 为什么打印 255

c - 在c中使用qsort进行排序

python - 在 Python 中捕获 SIGINT 以外的信号

c - 构建期间的警告消息 --> 警告 : "bool" redefined

linux - 使用ffmpeg drawtext作为rtl语言的问题

objective-c - 为什么信号不会被捕获?