父进程退出后如何通知子进程退出

本文介绍如何在Linux中使用prctl系统调用来使父进程能在意外终止时通知其子进程。通过设置特定信号,即使父进程崩溃也能确保子进程得到通知并采取相应措施。

Linux 中创建子进程是相当方便的,通过fork调用即可。当子进程退出时,要给父进程发送SIG_CHLD信号,是为了父进程回收子进程的资源,方便管理的目的。 但是当父进程退出后,一般是不会通知子进程的,父进程会将自己的所有子进程过继给init进程。

但是,在实际的项目中,我们有这样的需求: 如果父进程退出后,希望能通知子进程退出。

我们知道,可以利用进程间通信机制,在父进程退出前主动发送信号或pipe或其他手段告知子进程自己退出了。

但是,当父进程意外退出时,比如coredump了,根本没机会主动发送信号或pipe等消息的。

这时怎么办呢?

我们发现 prctl 这个调用, 通过man prctl:

PR_SET_PDEATHSIG (since Linux 2.1.57)
          Set  the parent process death signal of the calling process to arg2    (either a signal value in the range
          1..maxsig, or 0 to clear).  This is the signal that the calling process
          will get when its parent  dies.

据此, 我们可以在子进程中给父进程设置当父进程退出时子进程收到的信号。

prctl(PR_SET_PDEATHSIG, SIGHUP);

代码如下:

#include <stdio.h>
  #include <stdlib.h>
  #include <string.h>
  #include <sys/prctl.h>
  #include <signal.h>

  static int do_abort = 0;

  void handle_signal(int signo)
  {
      if (signo == SIGHUP)
      {                 
          printf("child recv SIGHUP..\n");
          do_abort = 1;
      }
  }

  int main(void)
  {
      pid_t pid;
      pid = fork();
      char *p = NULL;

      if (pid == 0) // child
      {
          signal(SIGHUP, handle_signal);
          prctl(PR_SET_PDEATHSIG, SIGHUP);
          while(!do_abort) {
              sleep(1);
              printf("in child...\n");
          }
          printf("child exit...\n");
          return 0;
      }
      else // parent
      {
          int times = 5;
          while(times -- > 0)
          {
              sleep(1);
              if (times == 3)
              {
                  printf("memcpy ...\n");
                  memcpy(p, "Hello", 5);
              }
              printf("in parent.\n");
          }

          printf("parent exit..\n");
          return 0;
      }

      return 0;
  }

通过测试,如果去掉 prctl调用,当父进程发生段错误退出后,子进程依然继续运行。 如果去掉signal调用,即子进程不捕获SIG_HUP信号,当父进程退出后依然会退出,只是退出的有些不优雅罢了。

### 在 Golang 中设置父进程退出后自动终止子进程的方法 在 Golang 中,可以使用 `prctl` 系统调用来设置子进程的行为,使其在父进程退出时自动终止。具体来说,可以通过设置 `PR_SET_PDEATHSIG` 选项来实现这一功能[^2]。 #### 使用 CGO 调用 `prctl` 以下是一个示例代码,展示如何通过 CGO 调用 `prctl` 来实现父进程退出后自动终止子进程的功能: ```go package main /* #include <sys/prctl.h> #include <signal.h> #include <stdlib.h> */ import "C" import ( "fmt" "os/exec" "syscall" ) func main() { // 设置子进程父进程退出时的行为 if err := C.prctl(C.PR_SET_PDEATHSIG, C.SIGKILL, 0, 0, 0); err != 0 { fmt.Println("Failed to set PR_SET_PDEATHSIG") return } // 启动子进程 cmd := exec.Command("sleep", "100") // 示例:启动一个长时间运行的子进程 cmd.SysProcAttr = &syscall.SysProcAttr{ Setpgid: true, // 将子进程放入新的进程组 } if err := cmd.Start(); err != nil { fmt.Printf("Failed to start command: %v\n", err) return } fmt.Println("Parent process exiting...") } ``` #### 使用 `syscall.RawSyscall` 调用 `prctl` 如果不希望通过 CGO 调用 `prctl`,也可以直接使用 Golang 的 `syscall.RawSyscall` 来调用系统调用。以下是示例代码: ```go package main import ( "fmt" "os/exec" "syscall" "unsafe" ) const ( PR_SET_PDEATHSIG = 1 ) func prctl(option int, arg2 uintptr) error { _, _, errno := syscall.RawSyscall(syscall.SYS_PRCTL, uintptr(option), arg2, 0) if errno != 0 { return errno } return nil } func main() { // 设置子进程父进程退出时的行为 if err := prctl(PR_SET_PDEATHSIG, uintptr(syscall.SIGKILL)); err != nil { fmt.Printf("Failed to set PR_SET_PDEATHSIG: %v\n", err) return } // 启动子进程 cmd := exec.Command("sleep", "100") // 示例:启动一个长时间运行的子进程 cmd.SysProcAttr = &syscall.SysProcAttr{ Setpgid: true, // 将子进程放入新的进程组 } if err := cmd.Start(); err != nil { fmt.Printf("Failed to start command: %v\n", err) return } fmt.Println("Parent process exiting...") } ``` #### 关键点说明 1. **`PR_SET_PDEATHSIG`**:此选项用于设置当父进程退出时,子进程将接收到的信号。例如,可以设置为 `SIGKILL`,使子进程父进程退出时立即终止。 2. **进程组管理**:为了确保子进程不会成为孤儿进程,通常会将其放入一个新的进程组(通过设置 `Setpgid: true`)[^2]。 3. **信号处理**:子进程可以根据接收到的信号决定其行为。例如,可以在子进程中捕获 `SIGKILL` 并执行清理操作。 #### 注意事项 - 如果希望子进程父进程退出后继续运行,则需要避免设置会导致子进程终止的信号(如 `SIGKILL`)[^2]。 - 在某些情况下,可能需要额外的逻辑来确保子进程能够正确地恢复运行[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值