使用 _exit() & 有什么区别?exit() 在传统的 Linux fork-exec 中? [英] What is the difference between using _exit() & exit() in a conventional Linux fork-exec?

查看:18
本文介绍了使用 _exit() & 有什么区别?exit() 在传统的 Linux fork-exec 中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直试图弄清楚 fork-exec 机制是如何在 Linux 中使用的.一切都按计划进行,直到一些网页开始让我感到困惑.

I've been trying to figure out how the fork-exec mechanism is used inside Linux. Everything was going on according to the plan until some web pages started to confuse me.

据说子进程应该严格使用_exit(),而不是简单的exit()或者从main()的正常返回代码>.

It is said that a child process should strictly use _exit() instead of a simple exit() or a normal return from main().

据我所知,Linux shell fork-exec 会执行每一个外部命令;假设我上面说的是真的,那么结论是这些外部命令和Linux shell内部发生的任何其他执行都不能正常返回!

As I know, Linux shell fork-execs every one of the external commands; assuming what I said above is true, the conclusion is that none of these external commands nor any other execution happening inside the Linux shell can do normal return!

维基百科和其他一些网页声称我们必须使用 _exit() 只是为了防止子进程导致删除父进程的临时文件,而可能会发生 stdio 缓冲区的双重刷新.虽然我理解前者,但我不知道缓冲区的双重刷新如何对 Linux 系统有害.

Wikipedia & some other webpages claim we've got to use _exit() just to prevent a child process causing deletion of parent's temporary files while a probable double flushing of stdio buffers may happen. though I understand the former, I have no clues how a double flushing of buffers could be harmful to a Linux system.

我已经花了一整天的时间...感谢您的澄清.

I've spent my whole day on this... Thanks for any clarification.

推荐答案

你应该使用 _exit(或其同义词_Exit)在exec失败时中止子程序,因为在这种情况下,子程序进程可能会通过调用其 atexit 处理程序、调用其信号处理程序和/或刷新缓冲区来干扰父进程的外部数据(文件).

You should use _exit (or its synonym _Exit) to abort the child program when the exec fails, because in this situation, the child process may interfere with the parent process' external data (files) by calling its atexit handlers, calling its signal handlers, and/or flushing buffers.

出于同样的原因,您也应该在任何不执行 exec 的子进程中使用 _exit,但这种情况很少见.

For the same reason, you should also use _exit in any child process that does not do an exec, but those are rare.

在所有其他情况下,只需使用 exit.正如您自己部分指出的那样,Unix/Linux 中的 每个 进程(除了一个,init)是另一个进程的子进程,因此在每个子进程都意味着 exitinit 之外是无用的.

In all other cases, just use exit. As you partially noted yourself, every process in Unix/Linux (except one, init) is the child of another process, so using _exit in every child process would mean that exit is useless outside of init.

switch (fork()) {
  case 0:
    // we're the child
    execlp("some", "program", NULL);
    _exit(1);  // <-- HERE
  case -1:
    // error, no fork done ...
  default:
    // we're the parent ...
}

这篇关于使用 _exit() &amp; 有什么区别?exit() 在传统的 Linux fork-exec 中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆