【问题标题】:Waitpid waiting on defunct child processWaitpid 等待失效的子进程
【发布时间】:2020-01-15 01:39:13
【问题描述】:

如果发生崩溃,我们会使用以下函数转储堆栈以获取有关崩溃的更多信息:

static void dumpStack()
    {
        char buf[64];

        pid_t pid = getpid();

        sprintf( buf, "%d", pid );

        pid_t fork_result = vfork();

        int status;

        if( fork_result == 0 )

            execlp( "pstack", "pstack", buf, NULL );

        else if( fork_result > 0 )

            waitpid( fork_result, &status, 0 );

        else

            std::cerr << "vfork failed with err=%s" << strerror( errno ) << std::endl;
    }

在上面的代码中,父母永远停留在 waitPid 上。我检查了它变成僵尸的子进程的状态:

Deepak@linuxPC:~$ ps aux | grep  21054

    700048982 21054 0.0  0.0      0     0 pts/0    Z+   03:01   0:00 [pstack] <defunct>

孩子打印的堆栈也不完整。它只打印一行并退出。

#0  0x00007f61cb48d26e in waitpid () from /lib64/libpthread.so.0

不知道为什么父母不能收获这个过程。

如果我在这里遗漏了什么,请您帮忙

【问题讨论】:

  • 你的意思是在父进程崩溃的情况下?这个函数将如何被调用?
  • 请提供一个完整的minimal reproducible example,可以按原样复制和编译来演示问题,而不仅仅是一个孤立的函数。
  • 您是从信号处理程序调用此函数吗?请注意,vfork 不是 listed 作为信号安全的,execlp 也不是。您可能可以使用特定于 Linux 的 backtrace 功能,但它没有被列为信号安全 either(但已在其他地方的信号示例中使用,例如 this one)。
  • 避免使用vfork,恕我直言,永远不要使用它

标签: c++ linux fork waitpid pstack


【解决方案1】:

首先,你最好使用 backtrace() 函数,见How to automatically generate a stacktrace when my program crashes

至于您的代码,如果您使用的是 64 位 Linux(可能),pstack 将无法工作。对我来说,它是段错误的。此外,我同意 vfork() 和 execlp() 上的 cmets。此外,您可能需要以 root 身份执行程序。下面的代码对我有用(打印父级的堆栈,但不确定这是否非常有用):

#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
#include <errno.h>

#include <iostream>
#include <system_error>

using std::cout;

static void dumpStack() {
  char buf[64];
  pid_t result;
  pid_t pid = getpid();
  sprintf(buf, "/proc/%d/stack", pid );
  //cout << buf << '\n';                                                                                                         
  pid_t fork_result = vfork();
  int status;
  if( fork_result == 0 ) {
    //execlp( "pstack", "pstack", buf, NULL );                                                                                   
    cout << "Child before execlp\n";
    execlp("cat", "cat", buf, NULL);
    cout << "Child after execlp\n";  // Will not print, of course
  } else if( fork_result > 0 ) {
    result = waitpid( fork_result, &status, 0 );
    if (result < 0) {
      throw std::system_error(errno, std::generic_category());
    }
  } else {
    std::cerr << "vfork failed with err=%s" << strerror( errno ) << std::endl;
  }
  cout << std::endl;
}

int main() {
  dumpStack();

  return 0;
}

【讨论】:

    猜你喜欢
    • 2020-09-09
    • 1970-01-01
    • 1970-01-01
    • 2012-07-02
    • 2015-02-24
    • 2016-03-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多