Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why waitpid return -1 when run in debugger?

I'm using fork to create a process on a Mac platform, and wait for the child process to finish in the parent process. But the waitpid return -1 and errno is 4 (EINTR).

The example code, which can reproduce this problem, is as follows:

#include <iostream>
#include <sys/types.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <assert.h>
int main(int argc, const char *argv[])
{
    pid_t pid = ::fork();
    if (pid == 0)
    {
        return 0;
    }

    int s = 0;
    if (::waitpid(pid, &s, 0) == -1)
    {
        printf("The errno is :%d\n", errno); // <<<The errno is 4(EINTR) in my machine.
        assert(false);  // <<<<This will be hit if run in debugger.
    }
    return 0;
}

When I run this code in GDB or LLDB the assert will always be hit. If not run in debugger it will not return -1.

I think there is something I don't understand about how debugger or fork/waitpid works. So can anyone explain why this happen?

like image 494
ZijingWu Avatar asked Nov 15 '25 23:11

ZijingWu


1 Answers

The debugger is sending a signal to the process. As WhozCraig said, these should be handled by detecting EINTR and calling waitpid again in a loop. Be aware that when running the child process in the debugger, the debugger likely changes the parent process to the debugger's PID, so waitpid on the child PID will fail thinking the child process has exited, even though it has not. When the debugger exits, it restores the PPID of the child to the original parent's PID.

like image 140
bu11d0zer Avatar answered Nov 18 '25 12:11

bu11d0zer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!