考虑以下代码片段:
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*/ } }当退出子进程时,最好写_exit而不是exit但是如果我需要调用外部函数并进入这个函数我想要退出,我该怎么写? _exit还是exit ?
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?
最满意答案
您可以期望exit调用使用atexit注册的函数。 _exit不会这样做。 通常,每个注册的清理处理程序应该只执行一次,通常是在它注册的过程中。 这意味着子进程应该_exit()而父进程应该exit() 。 如果子进程exec某些其他程序(这可能是最常见的情况),则该新程序将覆盖任何已注册的处理程序,这意味着您将返回exit() 。
至于外部函数:我会说你应该调用exit但是你应该准备好遇到奇怪的行为,如果父在执行fork之前注册了非平凡的东西atexit 。 所以尽量早点分叉,除非你的意思是对孩子exec 。 并着眼于您自己的代码和您使用的库可能安装的退出处理程序。 I / O缓冲区刷新就是一个例子。
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.
更多推荐
发布评论