Question

I'm trying to launch a linux service from a c++ and I do it successfully but one of my process is marked as "defunct" and I don't want that my parent process dies.

My code is (testRip.cpp):

int main()
{
    char* zebraArg[2];
    zebraArg[0] = (char *)"zebra";
    zebraArg[1] = (char *)"restart";

    char* ripdArg[2];
    ripdArg[0] = (char *)"ripd";
    ripdArg[1] = (char *)"restart";

    pid_t ripPid;
    pid_t zebraPid;

    zebraPid = fork();
    if(zebraPid == 0)
    {
        int32_t iExecvRes = 0;
        iExecvRes = execv("/etc/init.d/zebra", zebraArg);
        return 0;

        if(iExecvRes == -1)
        {
        ::syslog((LOG_LOCAL0 | LOG_ERR),
            "zebra process failed \n");
        }
    }
    else
    {
        while(1)
        {
                ::syslog((LOG_LOCAL0 | LOG_ERR),
                 "running\n");
            sleep(2);
        }
    }
}

The exit of ps -e command is:

9411 pts/1    00:00:00 testRip
9412 pts/1    00:00:00 testRip <defunct>
9433 ?        00:00:00 zebra

The /etc/init.d/zebra launches the service as daemon or something like that so I think this is the trick but:

Why there are 3 processes and one of them is marked as defunct? What is wrong in my code? How can I fix it?

Thanks in advance.

Was it helpful?

Solution 2

Correctly forking a daemon process is hard in Unix and Linux because there are a lot of details to get right, and order is also important. I would suspect a combination of open file descriptors and not detatching the controlling terminal, in this case.

I would strongly suggest using a well-debugged implementation from another program - one of the reduced-functionality command line shells such as rsh or ksh may be a good choice, rather than trying to bake your own version.

OTHER TIPS

To remove zombies you the parent process must wait() its child or dies. If you need to make a non blocking wait() look at waitpid() with W_NOHANG flag.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top