为什么我们在 execvp 之后需要子退出?
我最近一直想知道为什么我们需要在执行 execvp 后执行子程序后使用 exit 。欢迎深入解释。
I have been recently wondering why do we need to use exit after the execution of a child after performing execvp. An in depth explannation is welcome.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您不需要让子进程在
execvp()
之后调用exit()
,但确保它确实这样做通常是明智的所以。如此之多,以至于支持将其作为一项规则提供给新手。当对 execvp() 或其他 exec 函数之一的调用成功时,它会用新的进程映像替换当前运行的进程映像。因此,这些函数不会成功返回,在这种情况下,接下来的内容都不重要。那么,问题完全在于当
exec*
调用失败时该怎么办。如果在 exec 失败时不退出子进程,那么它将继续运行父进程的代码。这很少是有意或想要的。它可能会做一些原本不想做的工作,通过不立即退出来延迟父级(通常是 wait() ),并最终以不正确的退出状态误导父级。反映实际发生的事情。
所有这些,也许还有更多,都可以通过确保
exec*
调用之后的控制流很快达到程序终止并出现故障状态(通常通过_Exit()
或_exit()
;较少通过exit()
或abort()
)。根据具体情况,在退出之前发出诊断消息或执行某种其他类型的清理可能合适,也可能不合适。You do not need for the child to call
exit()
afterexecvp()
, but it is often wise for you to ensure that it does so. So much so as to support giving that to novices as a rule.When a call to
execvp()
or one of the other exec functions succeeds, it has the effect of replacing the currently-running process image with a new one. As a result, these functions do not return on success, and nothing that follows matters in that case. The issue, then, is entirely about what to do in the event that theexec*
call fails.If you do not exit the child in the event that an exec fails then it will continue running the code of the parent. That is rarely intended or wanted. It may do work that it was not intended to do, delay the parent (that is often
wait()
ing for it) by not exiting promptly, and eventually mislead the parent with an exit status that is not reflective of what actually happened.All of that, and perhaps more, is addressed by ensuring that the control flow following an
exec*
call pretty quickly reaches program termination with a failure status (typically via_Exit()
or_exit()
; less typically viaexit()
orabort()
). Depending on the circumstances, it may or may not be appropriate to emit a diagnostic message before exiting, or to perform some other kind of cleanup.