how to exit a child process - _exit() vs. exit

前端 未结 5 825
粉色の甜心
粉色の甜心 2020-11-29 19:24

Consider this code snippet:

pid_t cpid = fork();

if (cpid == -1) {
    perror(\"fork\");
    exit(EXIT_FAILURE);
}

if (cpid == 0) { // in child
    execvp(         


        
相关标签:
5条回答
  • 2020-11-29 19:53

    exit() is ANSI-C function and therefore, it is operating system independent. It closes all ANSI-C standard functions. _exit() is called by exit() to close operating system-dependent functionalities, because exit() has no idea about them.(exit is operating system independent)

    0 讨论(0)
  • 2020-11-29 19:54

    You should definitely use _Exit(). exit() calls the functions you added with atexit() and deletes files created with tmpfile(). Since the parent process is really the one that wants these things done when it exists, you should call _Exit(), which does none of these.

    Notice _Exit() with a capital E. _exit(2) is probably not what you want to call directly. exit(3) and _Exit(3) will call this for you. If you don't have _Exit(3), then yes, _exit() is what you wanted.

    0 讨论(0)
  • 2020-11-29 19:58

    execvp will exit the child if successfull so you don't have to exit.

    On execve failure I simply use exit(EXIT_FAILURE); in the child.

    Edit : i found that after some research : http://www.unixguide.net/unix/programming/1.1.3.shtml

    So it's looks like it's better to use _exit() in a fork child specially when you are in C++ :p Thanks for your question i learned something :D

    0 讨论(0)
  • 2020-11-29 20:00

    It depends on the behavior you want: man -s 3 exit and man _exit for more details on your system. In general I believe the _exit doesn't run functions that are registered with atexit() whereas exit does (these functions better not call exit - otherwise you get recursion).

    In general I would prefer exit over _exit except for in functions registered with atexit, in those I would call _exit, if needed.

    0 讨论(0)
  • 2020-11-29 20:11

    The child of fork() should always call _exit().

    Calling exit() instead is a good way to cause pending stdio buffers to be flushed twice.

    0 讨论(0)
提交回复
热议问题