从子进程退出(c) [英] exit from a child process (c)

查看:76
本文介绍了从子进程退出(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,但是如果我需要调用外部函数并想在此函数中退出,我应该写些什么? _exitexit?

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().

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().

关于外部函数:我想说您应该调用exit,但是如果父级在进行派生之前注册了非平凡的东西atexit,您应该准备遇到奇怪的行为.因此,除非您打算在孩子中使用exec,否则请尽早分叉.并注意哪些退出处理程序将自己的代码以及所使用的库安装. I/O缓冲区刷新是一个示例.

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.

这篇关于从子进程退出(c)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆