退出子进程(c)(exit from a child process (c))

编程入门 行业动态 更新时间:2024-10-26 16:27:55
退出子进程(c)(exit from a child process (c))

考虑以下代码片段:

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.

更多推荐

本文发布于:2023-04-29 12:35:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1336422.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:进程   exit   process   child

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!