[英]How to control execution of parent process after execl() call in C program?
I have simple C program which executes an application using fork() and execl(). 我有一个简单的C程序,它使用fork()和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. 如果execl()无法运行该应用程序,那么我必须在父进程中调用一个函数并退出子进程。 If execl() successfully runs the application, then I have show a success log from the parent process. 如果execl()成功运行该应用程序,那么我已经显示了来自父进程的成功日志。 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. 因此,父进程应等待子进程的execl()调用(只是该调用,直到应用程序执行结束为止),获取有关其状态的一些信息,然后做出决定并继续自己的执行。 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. 我们知道execl()不会成功返回。 So, how to call HandleSuccessFromParent() and HandleFailureFromParent() functions properly after the execl() call in the child. 因此,如何在子对象中的execl()调用之后正确调用HandleSuccessFromParent()和HandleFailureFromParent()函数。 Please help me. 请帮我。
The child process needs to exit with an error status (non-zero; 1 is common, EXIT_FAILURE
is standard C). 子进程需要退出,并显示错误状态(非零; 1为通用, EXIT_FAILURE
为标准C)。
The parent process needs to wait for the child to finish, and capture the child's exit status, using wait()
or waitpid()
. 父进程需要等待子进程完成,并使用wait()
或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). 如果您需要知道孩子是否死亡,但又不想等待它完成,请在WNOHANG
停顿后将waitpid()
与WNOHANG
,以使孩子尝试运行(亚秒级的延迟可能足够长)。
One possible solution involves ptrace
. 一种可能的解决方案涉及ptrace
。 The outline is as follows: 概述如下:
Let the child call ptrace(PTRACE_TRACEME)
. 让子调用ptrace(PTRACE_TRACEME)
。 Let the parent enable PTRACE_O_TRACEEXEC
option and waitpid
on the child. 让家长能PTRACE_O_TRACEEXEC
选项, waitpid
的孩子。 In this setup waitpid
would return upon successful execl
. 在此设置中, waitpid
将在成功执行execl
返回。 Test the status to see if it has a SIGTRAP
flag set. 测试状态以查看是否设置了SIGTRAP
标志。 Let the child continue with PTRACE_DETACH
. 让孩子继续PTRACE_DETACH
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.