如何按给定顺序杀死 2 个子进程

How to kill 2 child processes in a given order

我想按给定的顺序终止子进程,但我的程序有时会输出正确的结果,有时不会。

任何人都可以请我做错了什么

正确顺序: 第一个 C 进程已终止。 第二个 C 进程已终止。 P 进程已终止。

有时得到这个输出: 第二个 C 进程已终止。 第一个 C 进程已终止。 P 进程已终止。

#include <signal.h>
#include <unistd.h>
#include <stdio.h>
#include <signal.h>
#include <stdlib.h>
#include <sys/wait.h>

pid_t child_pid = -1 ; //Global
pid_t child_pidb = -1 ; //Global

void kill_child(int sig) {

    kill(child_pid,SIGKILL);
}

void kill_childb(int sig){

    kill(child_pidb,SIGKILL);
}

int main(int argc, char *argv[])
{
   pid_t child_pid = fork();

    if (child_pid > 0) {
        
        pid_t child_pidb = fork();
        
        if(child_pidb>0) { 
            signal(SIGSTKFLT,(void (*)(int))kill_child);
            sleep(3);
            signal(SIGCHLD,(void (*)(int))kill_childb);
            wait(NULL);
             printf("P-process has terminated.");
             exit(0);
        }
        else if (child_pidb ==0 ) {
            printf("2nd C-process has terminated.");
        }
    }
    else if (child_pid == 0){
        printf("1st C-process has terminated.");
    }
}

仔细阅读两者signal(7) and signal-safety(7). And of course Advanced Linux Programming

考虑使用更简单的信号处理程序,每个信号处理程序只需设置一些声明为 volatile sigatomic_t gotsig;

的全局变量

然后编码一些finite state machine around sigpause(2) and/or waitpid(2)

另一种可能是使用 signalfd(2) with some event loop around poll(2)

重要的是在纸上画出您的有限自动机图并根据 transition system. You might view your signals (and other events like a process ending) as input to some parsing algorithm, probably an LL parser.

进行思考

学习一些open source shell, e.g. GNU bash or sash, and use strace(1) to understand its behavior in terms of syscalls(2)

代码的灵感

顺便说一句,你忘了处理一个重要的案例:fork(2) can fail. See errno(3) and perror(3).

请记住,几毫秒(或更多,在负载非常大的 Linux 系统上 - 请参阅 proc(5)) could happen between a process being terminated, and the corresponding waitpid to succeed. And with multi-core processors,您可能在两个不同的内核上有两个不同的进程 运行。

阅读credentials(7)