exec是否保留文件描述符 [英] Does exec preserve file descriptors

查看:265
本文介绍了exec是否保留文件描述符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这实际上是一个分为两个步骤的问题:

This is actually a two-step question:

  1. 什么是文件描述符?我认为这是代表打开文件的最基本方法.但是由于dup2可以使两个不同的文件描述符指向同一个文件,所以代表一个唯一文件的是什么?

  1. What exactly is a file descriptor? I thought it was the most fundamental way to represent an open file. But since dup2 can make two different file descriptors point to the same file, then what is it that represents a unique file?

如果我在exec之前执行dup2,则整个程序将被清除,它仍然具有相同的文件描述符表吗?重定向的文件描述符是否仍被重定向?

If I do dup2 before exec, the whole program is then wiped out, does it still have the same file descriptor table? Do the redirected file descriptors still are redirected?

推荐答案

.打开文件描述符在对exec的调用中保留.在 execve手册页中(所有exec*调用都只是对此的包装系统调用):

Yes. Open file descriptors are preserved across a call to exec. From the execve man page (all exec* calls are just a wrapper around this system call):

默认情况下,文件描述符在execve()中保持打开状态.标记为close-on-exec的文件描述符已关闭;参见fcntl(2)FD_CLOEXEC的说明.

By default, file descriptors remain open across an execve(). File descriptors that are marked close-on-exec are closed; see the description of FD_CLOEXEC in fcntl(2).

  1. 是的,文件描述符是用户空间引用的方式进行系统调用时打开文件. (或者套接字,管道等),可以复制它们的事实并不会改变这一点.它们只是对同一打开文件的多个引用.另请参阅:

  1. Yes, a file descriptor is the way that userspace refers to open files when making system calls. (Or socket, or pipe, etc.) The fact that they can be duplicated doesn't change that. They are simply multiple references to the same open file. See also:

  • Can I check if two FILE* or file descriptor numbers refer to the same file?
  • two file descriptors to same file

是的,如手册页引用中所述.

Yes, as mentioned in the man page quote.

实际上,许多程序(包括您的Shell)都依赖此功能.如果不是这样,您的程序将在没有打开标准输入/输出/错误文件描述符的情况下启动!当外壳程序运行程序时,它fork s,dup2的打开tty文件描述符为0,1,2,然后execve的是您的新程序.

In fact, many programs (including your shell) rely upon this feature. If it wasn't so, your program would start up without the standard in/out/error file descriptors open! When the shell runs a program, it forks, dup2's the open tty file descriptors to 0,1,2, and then execve's your new program.

这篇关于exec是否保留文件描述符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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