Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

exit() or _exit()?

Tags:

c

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?

like image 492
polslinux Avatar asked Sep 18 '25 12:09

polslinux


1 Answers

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.

like image 129
MvG Avatar answered Sep 20 '25 04:09

MvG