Consider this snippet of code:
void do_child(void);
int main(void){
int n;
pid_t child;
printf("Write a number: ");
scanf("%d", &n);
if(n != 1){
exit(1);
}
child = fork();
if(child >= 0){ /* fork ok */
if(child == 0){
printf("Child pid: %d\n", getpid());
do_child();
_exit(0);
}
else{ /* parent */
printf("Child parent: %d\n", getpid());
_exit(0);
}
}
else{ /* fallito */
perror("No fork");
return 1;
}
return EXIT_SUCCESS;
}
void do_child(void){
/* some code here */
if(1 != 1){
/* what to write here?? _exit or exit*/
}
}
When exiting from a child process it is best to write _exit
instead of exit
but if i need to call an external function and into this function i want to put an exit, what should i write? _exit
or exit
?
You can expect exit
to call functions registered with atexit
. _exit
won't do that. Normally, each registered cleanup handler should be executed exactly once, usually in the process in which it was registered. This means that a child process should _exit()
and the parent should exit()
. If the child process does exec
some other program, which is probably the most common case, then that new program will overwrite any registered handlers, which means that you are back to exit()
.
As to external functions: I'd say you should call exit
but you should be prepared to encounter strange behaviour if the parent registers non-trivial stuff atexit
before doing the fork. So try to fork early unless you mean to exec
in the child. And have an eye on what exit handlers your own code and the libraries you use might install. I/O buffer flushing is one example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With