为什么我们在 execvp 之后需要子退出?

发布于 2025-01-09 05:37:43 字数 56 浏览 2 评论 0原文

我最近一直想知道为什么我们需要在执行 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

晚雾 2025-01-16 05:37:43

不需要让子进程在execvp()之后调用exit(),但确保它确实这样做通常是明智的所以。如此之多,以至于支持将其作为一项规则提供给新手。

当对 execvp() 或其他 exec 函数之一的调用成功时,它会用新的进程映像替换当前运行的进程映像。因此,这些函数不会成功返回,在这种情况下,接下来的内容都不重要。那么,问题完全在于当 exec* 调用失败时该怎么办。

如果在 exec 失败时不退出子进程,那么它将继续运行父进程的代码。这很少是有意或想要的。它可能会做一些原本不想做的工作,通过不立即退出来延迟父级(通常是 wait() ),并最终以不正确的退出状态误导父级。反映实际发生的事情。

所有这些,也许还有更多,都可以通过确保 exec* 调用之后的控制流很快达到程序终止并出现故障状态(通常通过 _Exit()_exit();较少通过 exit()abort())。根据具体情况,在退出之前发出诊断消息或执行某种其他类型的清理可能合适,也可能不合适。

You do not need for the child to call exit() after execvp(), 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 the exec* 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 via exit() or abort()). 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文