Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

fork

process

Consider this code snippet:

pid_t cpid = fork();  if (cpid == -1) {     perror("fork");     exit(EXIT_FAILURE); }  if (cpid == 0) { // in child     execvp(argv[1], argv + 1);     perror("execvp");     _exit(EXIT_FAILURE); }  // in parent 

How shall I exit the child process if execvp returns? Shall I use exit() or _exit()?

like image 821
helpermethod Avatar asked Feb 24 '10 21:02

helpermethod


People also ask

What is the difference between exit () and _exit ()?

In this article Terminates the calling process. The exit function terminates it after cleanup; _exit and _Exit terminate it immediately.

How do you end a child process?

For killing a child process after a given timeout, we can use the timeout command. It runs the command passed to it and kills it with the SIGTERM signal after the given timeout. In case we want to send a different signal like SIGINT to the process, we can use the –signal flag.

How can I get leave status from Waitpid?

You can get the exit status of the child via the first argument of wait() , or the second argument of waitpid() , and then using the macros WIFEXITED and WEXITSTATUS with it. waitpid() will block until the process with the supplied process ID exits.

How do you use exit function?

The exit () function is used to break out of a loop. This function causes an immediate termination of the entire program done by the operation system. void exit (int code); The value of the code is returned to the calling process, which is done by an operation system.


2 Answers

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.

like image 189
Variable Length Coder Avatar answered Oct 04 '22 00:10

Variable Length Coder


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

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

like image 26
Joshua Avatar answered Oct 04 '22 00:10

Joshua