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.
One possible solution involves
ptrace
. The outline is as follows:Let the child call
ptrace(PTRACE_TRACEME)
. Let the parent enablePTRACE_O_TRACEEXEC
option andwaitpid
on the child. In this setupwaitpid
would return upon successfulexecl
. Test the status to see if it has aSIGTRAP
flag set. Let the child continue withPTRACE_DETACH
.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()
orwaitpid()
.If you need to know whether the child died but don't want to wait for it to complete, use
waitpid()
withWNOHANG
after a small pause to let the child try and run (a sub-second delay is likely to be long enough).