如何退出子进程 - _exit() 与退出 [英] how to exit a child process - _exit() vs. exit

查看:58
本文介绍了如何退出子进程 - _exit() 与退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个代码片段:

pid_t cpid = fork();

if (cpid == -1) {
    perror("fork");
    exit(EXIT_FAILURE);
}

if (cpid == 0) { // in child
    execvp(argv[1], argv + 1);
    perror("execvp");
    _exit(EXIT_FAILURE);
}

// in parent

如果 execvp 返回,我该如何退出子进程?我应该使用 exit() 还是 _exit() ?

How shall I exit the child process if execvp returns? Shall I use exit() or _exit()?

推荐答案

你绝对应该使用 _Exit().exit() 调用您使用 atexit() 添加的函数并删除使用 tmpfile() 创建的文件.由于父进程确实希望在它存在时完成这些事情,因此您应该调用 _Exit(),它不执行任何这些操作.

You should definitely use _Exit(). exit() calls the functions you added with atexit() and deletes files created with tmpfile(). Since the parent process is really the one that wants these things done when it exists, you should call _Exit(), which does none of these.

注意 _Exit() 带有大写字母 E._exit(2) 可能不是您想要直接调用的.exit(3)_Exit(3) 会为你调用这个.如果您没有 _Exit(3),那么是的,_exit() 就是您想要的.

Notice _Exit() with a capital E. _exit(2) is probably not what you want to call directly. exit(3) and _Exit(3) will call this for you. If you don't have _Exit(3), then yes, _exit() is what you wanted.

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

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