我正在使用叉子和管道.当父进程突然中止时,子进程不会被终止(例如分段错误)

  • 本文关键字:子进程 终止 错误 分段 进程 突然 管道 c
  • 更新时间 :
  • 英文 :


我正在使用fork来创建子进程和父进程,并使用管道在它们之间发送和接收消息。我正在运行带有一些输入的父进程,它调用子进程。如果父进程成功执行,子进程会自动被杀死,但是如果我在父进程运行时按 ctrl+c 或有任何分段错误,父进程会被杀死,但子进程不会被杀死。

任何人都可以向我发布父进程突然时杀死子进程的逻辑吗?

由于您已经使用管道进行通信,因此这应该很容易。

管道读取块,直到有数据要读取,如果父进程是写入器并且死亡,则立即EOF。如果您的父进程从未关闭其写入结束,那么您有一种可靠的方法来检测死亡。

管道写入命中SIGPIPE,如果没有读取器时忽略信号,则从调用中返回EPIPE

在子项中,选择(如果可以阻止)管道的fd,并在适当的时候杀死进程。没有SIGCHLD等同于父母死亡。

man 7 pipe有一个很好的概述。摘录:

If  all file descriptors referring to the write end of a pipe have been closed, then an attempt to read(2) from
the pipe will see end-of-file (read(2) will return 0).  If all file descriptors referring to the read end of  a
pipe have been closed, then a write(2) will cause a SIGPIPE signal to be generated for the calling process.  If
the calling process is ignoring this signal, then write(2) fails with the error  EPIPE.   An  application  that
uses  pipe(2)  and  fork(2) should use suitable close(2) calls to close unnecessary duplicate file descriptors;
this ensures that end-of-file and SIGPIPE/EPIPE are delivered when appropriate.

最新更新