Search code examples
c++linuxposixchild-processspawn

posix_spawn creates a zombie process and returns success


I'm trying to spawn a child process with posix_spawn(). I give the executable name (which exists) but posix_spawn() creates a zombie process (I search the process in ps and it shows as <defunct>). Even when I specify a non-existent executable name, the zombie process is created.

My problem is that I need to know whether the process was spawned successfully or not, but since posix_spawn returns 0 (success) and child process' id is valid, I have no way to be notified that an error occurred.

Here's my code (P.S. the executable "dummy" doesn't exist):

#include <iostream>
#include <spawn.h>

extern char **environ;

int main()
{
    const char *args[] = { "dummy", nullptr };

    pid_t pid = 0;

    posix_spawn(&pid, "dummy", nullptr, nullptr, const_cast<char **>(args), environ);
    if (pid == 0)
    {
        // doesn't get here
    }
    else
        // this gets executed instead, pid has some value
        std::cout << pid << std::endl;
}

With getting status:

#include <iostream>
#include <spawn.h>

extern char **environ;

int main()
{
    const char *args[] = { "dummy", nullptr };

    int status = posix_spawn(nullptr, "dummy", nullptr, nullptr, const_cast<char **>(args), environ);
    if (status != 0)
    {
        // doesn't get here
    }
    else
        // this gets executed, status is 0
        std::cout << status << std::endl;
}

Solution

  • A child process being a zombie means it finished/died and you need to reap its exit status with wait/waitpid.

    #include <sys/wait.h>
    //...
    int wstatus; 
    waitpid(pid,&wstatus,0);