How to control execution of parent process after e

2019-08-06 21:46发布

I have simple C program which executes an application using fork() and execl(). If execl() fails to run the application, then I have to call a function in the parent process and exit from the child process. If execl() successfully runs the application, then I have show a success log from the parent process. So, parent process should wait for the child's execl() call (just the call, not till the end of execution of the application), get some information about it status, and then make decisions and continue its own execution. Here is my code.

int main()
{
    int iExecRetVal, pid;
    pid = fork();

    if (pid == -1)
    {

    }
    else if (pid > 0)
    {
    }
    else
    {
        iExecRetVal = execl("./flute-static", "./flute-static", "-send", "-a192.168.190.1/6666", "JFlute.1.2.tar.gz", NULL);
        if (iExecRetVal == -1)
        {
            /*execl() failed, need some error handling in the parent process*/
        }
        _exit(0);
    }

    /*Parent's normal execution*/
}

int HandleSuccessFromParent()
{
    /*Should be called when exec call was successful*/
}

int HandleFailureFromParent()
{
    /*Should be called when exec call was NOT successful*/
}

We know execl() does not return on success. So, how to call HandleSuccessFromParent() and HandleFailureFromParent() functions properly after the execl() call in the child. Please help me.

2条回答
beautiful°
2楼-- · 2019-08-06 22:29

One possible solution involves ptrace. The outline is as follows:

Let the child call ptrace(PTRACE_TRACEME). Let the parent enable PTRACE_O_TRACEEXEC option and waitpid on the child. In this setup waitpid would return upon successful execl. Test the status to see if it has a SIGTRAP flag set. Let the child continue with PTRACE_DETACH.

查看更多
Juvenile、少年°
3楼-- · 2019-08-06 22:31

The child process needs to exit with an error status (non-zero; 1 is common, EXIT_FAILURE is standard C).

The parent process needs to wait for the child to finish, and capture the child's exit status, using wait() or waitpid().

If you need to know whether the child died but don't want to wait for it to complete, use waitpid() with WNOHANG after a small pause to let the child try and run (a sub-second delay is likely to be long enough).

查看更多
登录 后发表回答