在 main 中等待 execvp
int main()
{
...
if(!fork())
{
execvp(cmdName,cmdParam);
}
printf("In main()...");
return(0);
}
- 假设我已经正确传递了 cmdName & cmdParam 参数,在恢复 main() 的执行之前,如何等待 execvp 创建的进程完成?
- execvp() 是否创建一个新进程 fork() 的子进程?
int main()
{
...
if(!fork())
{
execvp(cmdName,cmdParam);
}
printf("In main()...");
return(0);
}
- Assuming I have correctly passed the cmdName & cmdParam arguments, how do I wait for the process created by execvp to finish, before resuming the execution of main()?
- Does the execvp() create a process which is a child of the newly fork()ed process?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在父进程中,
fork
返回子进程的PID,因此您可以将其存储在变量中,然后使用waitpid
等待子进程并非如此 - 由
fork
创建的新子进程是父进程的副本,然后execvp
将其进程映像替换为新映像。实际上,您最初拥有父进程的两个“副本”,其中一个随后“成为”新程序。事实
In the parent process,
fork
returns the PID of the child process, so you can store that in a variable, and then usewaitpid
to wait for the child process to terminate.Not really - the new child process created by
fork
is a duplicate of the parent, andexecvp
then replaces its process image with a new image. Effectively you initially have two 'copies' of the parent, one of which then 'becomes' the new program.如前所述,您需要保存 fork 调用的值。你真的应该在叉子上使用比 if 更多的东西。分三种情况:
你真的很想了解情况 3,它会毁了你一整天。 (也是 exec 调用)
return(0);
}
As noted you need to save the value of the fork call. You should really use more than an if on the fork. There are three cases:
You really want to know about case 3, it'll ruin your whole day. (also the exec call)
return(0);
}
对于你的第一个问题:
像这样使用 waitpid(2) :
对于第二部分:所有 exec 函数调用都接管进程(它们都不返回)
For your first question:
Use waitpid(2) like this:
For the second part: all exec function calls take the process over (none of them return)
您需要存储
fork()
的返回值,该值向每个可执行文件返回不同的值(如果您是子PID,如果您是父PID,则返回0),然后您需要执行<代码>waitpidYou need to store the return value of
fork()
, which returns a different value to each executable (0 if you are the child PID if you are the parent), and then you need to do awaitpid