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
exitto call functions registered withatexit._exitwon’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 shouldexit(). If the child process doesexecsome other program, which is probably the most common case, then that new program will overwrite any registered handlers, which means that you are back toexit().As to external functions: I’d say you should call
exitbut you should be prepared to encounter strange behaviour if the parent registers non-trivial stuffatexitbefore doing the fork. So try to fork early unless you mean toexecin 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.