5、FileDescriptor的源码和使用注意事项(windows操作系统,JDK8)

  操作系统使用文件描述符来指代一个打开的文件,对文件的读写操作,都需要文件描述符指向存储设备的不透明标识符。Java虽然在设计上使用了抽象程度更高的流来作为文件操作的模型,但是底层依然要使用文件描述符与操作系统交互,而Java世界里文件描述符的对应类就是FileDescriptor。同时,Java规定了FileDescriptor只能由JDK的其它类来创建(比如FileInputStream、FileOutputStream、RandomAccessFile等),不能由应用程序自己创建。
  操作系统中的文件描述符本质上是一个非负整数,其中0,1,2固定为标准输入,标准输出,标准错误输出,如下所示(POSIX标准):
clipboard
  Java程序接打开的文件使用当前进程可用的文件描述符就被保存在了FileDescriptor中的int fd变量,因此FileDescriptor的核心功能都是围绕着int fd变量来运行的

package java.io;
import java.util.ArrayList;
import java.util.List;
public final class FileDescriptor {

    private int fd;

    private long handle;

    private Closeable parent;
    private List<Closeable> otherParents;
    private boolean closed;
    
    //FileDescriptor只有无参的构造函数,保证了fd不能被应用程序设置
    public /**/ FileDescriptor() {
        fd = -1;
        handle = -1;
    }

    static {
        initIDs();
    }

    static {
        sun.misc.SharedSecrets.setJavaIOFileDescriptorAccess(
            new sun.misc.JavaIOFileDescriptorAccess() {
                public void set(FileDescriptor obj, int fd) {
                    obj.fd = fd;
                }

                public int get(FileDescriptor obj) {
                    return obj.fd;
                }

                public void setHandle(FileDescriptor obj, long handle) {
                    obj.handle = handle;
                }

                public long getHandle(FileDescriptor obj) {
                    return obj.handle;
                }
            }
        );
    }
    //POSIX标准中的标准输入,和System.class有关
    public static final FileDescriptor in = standardStream(0);
    //POSIX标准中的标准输出,和System.class有关
    public static final FileDescriptor out = standardStream(1);
    //POSIX标准中的标准错误输出,和System.class有关
    public static final FileDescriptor err = standardStream(2);

    public boolean valid() {
        return ((handle != -1) || (fd != -1));
    }

    public native void sync() throws SyncFailedException;

    private static native void initIDs();

    private static native long set(int d);

    private static FileDescriptor standardStream(int fd) {
        FileDescriptor desc = new FileDescriptor();
        desc.handle = set(fd);
        return desc;
    }

    synchronized void attach(Closeable c) {
        if (parent == null) {
            // first caller gets to do this
            parent = c;
        } else if (otherParents == null) {
            otherParents = new ArrayList<>();
            otherParents.add(parent);
            otherParents.add(c);
        } else {
            otherParents.add(c);
        }
    }

    @SuppressWarnings("try")
    synchronized void closeAll(Closeable releaser) throws IOException {
        if (!closed) {
            closed = true;
            IOException ioe = null;
            try (Closeable c = releaser) {
                if (otherParents != null) {
                    for (Closeable referent : otherParents) {
                        try {
                            referent.close();
                        } catch(IOException x) {
                            if (ioe == null) {
                                ioe = x;
                            } else {
                                ioe.addSuppressed(x);
                            }
                        }
                    }
                }
            } catch(IOException ex) {
                /*
                 * If releaser close() throws IOException
                 * add other exceptions as suppressed.
                 */
                if (ioe != null)
                    ex.addSuppressed(ioe);
                ioe = ex;
            } finally {
                if (ioe != null)
                    throw ioe;
            }
        }
    }
}

一、设置int fd变量的值

  FileDescriptor.class 的构造函数将int fd的值设置为了-1,但是操作系统中的文件描述符本质上是一个非负整数,因此FileDescriptor.class中表示文件描述符的int fd变量是在FileInputStream.class、FileOutputStream.class、RandomAccessFile.class等这些使用FileDescriptor.class的类中来设置的,比如FileInputStream.class

public
class FileInputStream extends InputStream
{
    /* File Descriptor - handle to the open file */
    private final FileDescriptor fd;
    
    //在FileInputStream实例化时,会新建FileDescriptor实例,并使用fd.attach(this)关联FileInputStream实例与FileDescriptor实例,这是为了之后在程序中关闭文件描述符做准备。
    public FileInputStream(File file) throws FileNotFoundException {
        String name = (file != null ? file.getPath() : null);
        ...省略代码...
        fd = new FileDescriptor();
        fd.attach(this);
        path = name;
        open(name);
    }
    
    private void open(String name) throws FileNotFoundException {
        open0(name);
    }
    //真正对FileDescriptor.class中int fd赋值的逻辑是JNI调用的FileInputStream#open0这个native函数中
    private native void open0(String name) throws FileNotFoundException;
}
// /jdk/src/share/native/java/io/FileInputStream.c
JNIEXPORT void JNICALL
Java_java_io_FileInputStream_open(JNIEnv *env, jobject this, jstring path) {
    fileOpen(env, this, path, fis_fd, O_RDONLY);
}

// /jdk/src/solaris/native/java/io/io_util_md.c
void
fileOpen(JNIEnv *env, jobject this, jstring path, jfieldID fid, int flags)
{
    WITH_PLATFORM_STRING(env, path, ps) {
        FD fd;

#if defined(__linux__) || defined(_ALLBSD_SOURCE)
        /* Remove trailing slashes, since the kernel won't */
        char *p = (char *)ps + strlen(ps) - 1;
        while ((p > ps) && (*p == '/'))
            *p-- = '\0';
#endif
        fd = JVM_Open(ps, flags, 0666); // 打开文件拿到文件描述符
        if (fd >= 0) {
            SET_FD(this, fd, fid); // 非负整数认为是正确的文件描述符,设置到fd变量
        } else {
            throwFileNotFoundException(env, path);  // 负数认为是不正确文件描述符,抛出FileNotFoundException异常
        }
    } END_PLATFORM_STRING(env, ps);
}

  到了JDK的JNI代码中,使用JVM_Open打开文件,得到文件描述符,而JVM_Open已经不是JDK的方法了,而是JVM提供的方法,所以需要继续查看hotspot中的实现:

// /hotspot/src/share/vm/prims/jvm.cpp
JVM_LEAF(jint, JVM_Open(const char *fname, jint flags, jint mode))
  JVMWrapper2("JVM_Open (%s)", fname);

  //%note jvm_r6
  int result = os::open(fname, flags, mode);  // 调用os::open打开文件
  if (result >= 0) {
    return result;
  } else {
    switch(errno) {
      case EEXIST:
        return JVM_EEXIST;
      default:
        return -1;
    }
  }
JVM_END

// /hotspot/src/os/linux/vm/os_linux.cpp
int os::open(const char *path, int oflag, int mode) {

  if (strlen(path) > MAX_PATH - 1) {
    errno = ENAMETOOLONG;
    return -1;
  }
  int fd;
  int o_delete = (oflag & O_DELETE);
  oflag = oflag & ~O_DELETE;

  fd = ::open64(path, oflag, mode);  // 调用open64打开文件
  if (fd == -1) return -1;

  // 问打开成功也可能是目录,这里还需要判断是否打开的是普通文件
  {
    struct stat64 buf64;
    int ret = ::fstat64(fd, &buf64);
    int st_mode = buf64.st_mode;

    if (ret != -1) {
      if ((st_mode & S_IFMT) == S_IFDIR) {
        errno = EISDIR;
        ::close(fd);
        return -1;
      }
    } else {
      ::close(fd);
      return -1;
    }
  }

#ifdef FD_CLOEXEC
    {
        int flags = ::fcntl(fd, F_GETFD);
        if (flags != -1)
            ::fcntl(fd, F_SETFD, flags | FD_CLOEXEC);
    }
#endif

  if (o_delete != 0) {
    ::unlink(path);
  }
  return fd;
}

可以看到JVM最后使用open64这个函数打开文件,网上对于open64这个资料还是很少的,我找到的是man page for open64 (all section 2) - Unix & Linux Commands,从中可以看出,open64是为了在32位环境打开大文件的系统调用,但是不是标准的一部分。(这一部分不是很确定,因为没有明确的资料)
  这里的open()函数不是我们以前学C语言时打开文件用的fopen()函数,fopen是C标准库里的函数,而open()不是,open()是POSIX规范中的函数,是不带缓冲的I/O,不带缓冲的I/O相关的函数还有read(),write(),lseek(),close(),不带缓冲指的是这些函数都调用内核中的一个系统调用,而C标准库为了减少系统调用,使用了缓存来减少read,write的内存调用。(参考《UNIX环境高级编程》)
  因此,我们知道了FileInputStream#open是使用open()系统调用来打开文件,得到文件句柄,现在我们的问题要回到这个文件句柄是如何最终设置到FileDescriptor#fd,我们来看/jdk/src/solaris/native/java/io/io_util_md.c:fileOpen的关键代码:

fd = handleOpen(ps, flags, 0666);
if (fd != -1) {
    SET_FD(this, fd, fid);
} else {
    throwFileNotFoundException(env, path);
}

如果文件描述符fd正确,通过SET_FD这个红设置到fid对应的成员变量上,如下宏所示:

#define SET_FD(this, fd, fid) \
    if ((*env)->GetObjectField(env, (this), (fid)) != NULL) \
        (*env)->SetIntField(env, (*env)->GetObjectField(env, (this), (fid)),IO_fd_fdID, (fd))

SET_FD宏比较简单,获取FileInputStream上的fid这个变量ID对应的变量,然后设置这个变量的IO_fd_fdID对应的变量(FileDescriptor#fd)为文件描述符。

  这个fid和IO_fd_fdID的来历可以参照/jdk/src/share/native/java/io/FileInputStream.c文件的开头,可以看到这样的代码:

// jdk/src/share/native/java/io/FileInputStream.c
jfieldID fis_fd; /* id for jobject 'fd' in java.io.FileInputStream */

/**************************************************************
 * static methods to store field ID's in initializers
 */

JNIEXPORT void JNICALL
Java_java_io_FileInputStream_initIDs(JNIEnv *env, jclass fdClass) {
    fis_fd = (*env)->GetFieldID(env, fdClass, "fd", "Ljava/io/FileDescriptor;");
}

Java_java_io_FileInputStream_initIDs对应JAVA中FileInputStream.class源码中的static块调用的initIDs函数:

public
class FileInputStream extends InputStream
{
    /* File Descriptor - handle to the open file */
    private final FileDescriptor fd;
    static {
        initIDs();
    }
    private static native void initIDs();
}

还有jdk/src/solaris/native/java/io/FileDescriptor_md.c开头:

// jdk/src/solaris/native/java/io/FileDescriptor_md.c
/* field id for jint 'fd' in java.io.FileDescriptor */
jfieldID IO_fd_fdID;

/**************************************************************
 * static methods to store field ID's in initializers
 */

JNIEXPORT void JNICALL
Java_java_io_FileDescriptor_initIDs(JNIEnv *env, jclass fdClass) {
    IO_fd_fdID = (*env)->GetFieldID(env, fdClass, "fd", "I");
}

Java_java_io_FileDescriptor_initIDs对应JAVA中FileDescriptor.class源码中static块调用的initIDs函数:

public final class FileDescriptor {
    private int fd;
    static {
        initIDs();
    }
    private static native void initIDs();    
}

以上代码的整个流程为:
①、JVM加载FileDescriptor类,执行static块中的代码
②、执行static块中的代码时,执行initIDs本地函数
③、initIDs本地函数只做了一件事情,就是获取fd字段ID,并保存在IO_fd_fdID变量中
④、JVM加载FileInputStream类,执行static块中的代码
⑤、执行static块中的代码时,执行initIDs本地函数
⑥、initIDs本地函数只做了一件事情,就是获取fd字段ID,并保存在fis_fd变量中
⑦、后续逻辑直接使用IO_fd_fdID和fis_fd
  这样做的理由是因为特定类的字段ID在一次Java程序的声明周期中是不会变化的,而获取字段ID本身是一个比较耗时的过程,因为如果字段是从父类继承而来,JVM需要遍历继承树来找到这个字段,所以JNI代码的最佳实践就是对使用到的字段ID做缓存。

二、设置FileDescriptor in、FileDescriptor out、FileDescriptor err变量

  标准输入,标准输出,标准错误输出是所有操作系统都支持的,对于一个进程来说,文件描述符0,1,2固定是标准输入,标准输出,标准错误输出。Java对标准输入,标准输出,标准错误输出的支持也是通过FileDescriptor实现的,FileDescriptor中定义了FileDescriptor in、FileDescriptor out、FileDescriptor err这三个静态变量:

public final class FileDescriptor {
    //POSIX标准中的标准输入,和System.class有关
    public static final FileDescriptor in = standardStream(0);
    //POSIX标准中的标准输出,和System.class有关
    public static final FileDescriptor out = standardStream(1);
    //POSIX标准中的标准错误输出,和System.class有关
    public static final FileDescriptor err = standardStream(2);
}

我们常用的System.out、System.err等,就是基于这三个封装的:

public final class System {
    public final static PrintStream err = null;
    public final static InputStream in = null;
    public final static PrintStream out = null;
    private static void initializeSystemClass() {
        ...省略部分代码...
        FileInputStream fdIn = new FileInputStream(FileDescriptor.in);
        FileOutputStream fdOut = new FileOutputStream(FileDescriptor.out);
        FileOutputStream fdErr = new FileOutputStream(FileDescriptor.err);
        setIn0(new BufferedInputStream(fdIn));
        setOut0(newPrintStream(fdOut, props.getProperty("sun.stdout.encoding")));
        setErr0(newPrintStream(fdErr, props.getProperty("sun.stderr.encoding")));
        ...省略部分代码...
    }
    
    private static native void setIn0(InputStream in);
    private static native void setOut0(PrintStream out);
    private static native void setErr0(PrintStream err);
}

System.class作为一个特殊的类,该类构造时无法实例化PrintStream err变量、InputStream in变量、PrintStream out变量,构造发生在initializeSystemClass()函数被调用时,但是PrintStream err变量、InputStream in变量、PrintStream out变量是被声明为final的,如果声明时和类构造时没有赋值,是会报错的,所以System在实现时,先设置为null,然后通过native方法来在运行时修改(可以用在我的networkScan项目上),通过setIn0/setOut0/setErr0的注释也可以说明这一点:

/*
 * The following three functions implement setter methods for
 * java.lang.System.{in, out, err}. They are natively implemented
 * because they violate the semantics of the language (i.e. set final
 * variable).
 */
JNIEXPORT void JNICALL
Java_java_lang_System_setIn0(JNIEnv *env, jclass cla, jobject stream)
{
    jfieldID fid =
        (*env)->GetStaticFieldID(env,cla,"in","Ljava/io/InputStream;");
    if (fid == 0)
        return;
    (*env)->SetStaticObjectField(env,cla,fid,stream);
}

JNIEXPORT void JNICALL
Java_java_lang_System_setOut0(JNIEnv *env, jclass cla, jobject stream)
{
    jfieldID fid =
        (*env)->GetStaticFieldID(env,cla,"out","Ljava/io/PrintStream;");
    if (fid == 0)
        return;
    (*env)->SetStaticObjectField(env,cla,fid,stream);
}

JNIEXPORT void JNICALL
Java_java_lang_System_setErr0(JNIEnv *env, jclass cla, jobject stream)
{
    jfieldID fid =
        (*env)->GetStaticFieldID(env,cla,"err","Ljava/io/PrintStream;");
    if (fid == 0)
        return;
    (*env)->SetStaticObjectField(env,cla,fid,stream);
}

三、attach()函数和closeAll()函数

  attach()函数和closeAll()函数都和文件描述符的关闭有关。上文提到过,FileInputStream在构造函数中,会新建FileDescriptor并调用FileDescriptor#attach方法绑定文件流与文件描述符。

3.1、attach()函数
public
class FileInputStream extends InputStream
{
    /* File Descriptor - handle to the open file */
    private final FileDescriptor fd;
    private Closeable parent;
    private List<Closeable> otherParents;
    //在FileInputStream实例化时,会新建FileDescriptor实例,并使用fd.attach(this)关联FileInputStream实例与FileDescriptor实例,这是为了之后在程序中关闭文件描述符做准备。
    public FileInputStream(File file) throws FileNotFoundException {
        String name = (file != null ? file.getPath() : null);
        ...省略代码...
        fd = new FileDescriptor();
        fd.attach(this);
        path = name;
        open(name);
    }
    
    //如果FileDescriptor只和一个FileInputStream实例、FileOutputStream实例、RandomAccessFile等实例等有关联,
    //则只是简单的保存到parent成员中,如果有多个FileInputStream实例、FileOutputStream实例、RandomAccessFile等实例有关联,
    //则所有关联的Closeable都保存到List<Closeable> otherParents变量(实际是ArrayList<Closeable>实例)中。
    synchronized void attach(Closeable c) {
        if (parent == null) {
            // first caller gets to do this
            parent = c;
        } else if (otherParents == null) {
            otherParents = new ArrayList<>();
            otherParents.add(parent);
            otherParents.add(c);
        } else {
            otherParents.add(c);
        }
    }
}

  这里其实有个细节,就是Closeable parent变量其实只在这个函数有用到,所以上面的逻辑完全可以写成无论FileDescriptor和几个Closeable对象有关联,都直接保存到List otherParents变量即可,但是极大的概率,一个FileDescriptor只会和一个FileInputStream实例、FileOutputStream实例、RandomAccessFile等实例有关联,只有用户调用FileInputStream(FileDescriptor fdObj)这样样的构造函数才会出现多个Closeable对象对应一个FileDescriptor的情况,这里其实是做了优化,在大概率的情况下不新建ArrayList,减少一个对象的创建开销。

3.2、closeAll()函数
public
class FileInputStream extends InputStream
{
    /* File Descriptor - handle to the open file */
    private final FileDescriptor fd;
    private final Object closeLock = new Object();
    private volatile boolean closed = false;
    private FileChannel channel = null;
    public void close() throws IOException {
        synchronized (closeLock) {
            if (closed) {
                return;
            }
            closed = true;
        }
        if (channel != null) {
           channel.close();
        }
    
        fd.closeAll(new Closeable() {
            public void close() throws IOException {
               close0();
           }
        });
    }
    private native void close0() throws IOException;
}

  首先通过锁保证关闭流程不会被并发调用,设置成员变量boolean closed为true,接着关闭关联的Channel(NIO中的关键组件之一,另外2个NIO关键组件是Buffer、Selector)。接着就是关闭FileDescriptor了。
  FileDescriptor没有提供close()函数,而是提供了一个closeAll()函数:

synchronized void closeAll(Closeable releaser) throws IOException {
    if (!closed) {
        closed = true;
        IOException ioe = null;
        try (Closeable c = releaser) {
            if (otherParents != null) {
                for (Closeable referent : otherParents) {
                    try {
                        referent.close();
                    } catch(IOException x) {
                        if (ioe == null) {
                            ioe = x;
                        } else {
                            ioe.addSuppressed(x);
                        }
                    }
                }
            }
        } catch(IOException ex) {
            /*
             * If releaser close() throws IOException
             * add other exceptions as suppressed.
             */
            if (ioe != null)
                ex.addSuppressed(ioe);
            ioe = ex;
        } finally {
            if (ioe != null)
                throw ioe;
        }
    }
}

  FileDescriptor的关闭流程有点绕,效果是会把关联的Closeable对象(其实就是FileInputStream实例、FileOutputStream实例、RandomAccessFile等实例,而这些实例的close()函数实现是一模一样的)通通都关闭掉(效果是这些对象的成员变量boolean closed设置为true,关联的Channel关闭,这样这个对象就无法使用了),最后这些关联的对象中,只会有一个对象的close0本地函数被调用,这个函数中调用操作系统的close()函数来真正关闭文件描述符。

// /jdk/src/solaris/native/java/io/FileInputStream_md.c
JNIEXPORT void JNICALL
Java_java_io_FileInputStream_close0(JNIEnv *env, jobject this) {
    fileClose(env, this, fis_fd);
}

// /jdk/src/solaris/native/java/io/io_util_md.c
void fileClose(JNIEnv *env, jobject this, jfieldID fid)
{
    FD fd = GET_FD(this, fid);
    if (fd == -1) {
        return;
    }

    /* Set the fd to -1 before closing it so that the timing window
     * of other threads using the wrong fd (closed but recycled fd,
     * that gets re-opened with some other filename) is reduced.
     * Practically the chance of its occurance is low, however, we are
     * taking extra precaution over here.
     */
    SET_FD(this, -1, fid);

    // 尝试关闭0,1,2文件描述符,需要特殊的操作。首先这三个是不能关闭的,
    // 如果关闭的,后续打开的文件就会占用这三个描述符,
    // 所以合理的做法是把要关闭的描述符指向/dev/null,实现关闭的效果
    // 不过Java代码中,正常是没办法关闭0,1,2文件描述符的
    if (fd >= STDIN_FILENO && fd <= STDERR_FILENO) {
        int devnull = open("/dev/null", O_WRONLY);
        if (devnull < 0) {
            SET_FD(this, fd, fid); // restore fd
            JNU_ThrowIOExceptionWithLastError(env, "open /dev/null failed");
        } else {
            dup2(devnull, fd);
            close(devnull);
        }
    } else if (close(fd) == -1) { // 关闭非0,1,2的文件描述符只是调用close系统调用
        JNU_ThrowIOExceptionWithLastError(env, "close failed");
    }
}

四、不能将一个FileDescriptor对象给多个流用

伪代码如下所示:

    //new一个FileInputStream的流
    FileInputStream is = new FileInputStream("Some file");
    BufferedInputStream br = new BufferedInputStream(is);
    //获取流 is 的文件描述符fd
    FileDescriptor fd = is.getFD();
    //文件描述符fd在流 is 和流 is1之间共享使用
    FileInputStream is1 = new FileInputStream(fd);
    BufferedInputStream br1 = new BufferedInputStream(is1);

    is.close();//关闭流 is的文件描述符fd的同时也会关闭流 is1的文件描述符
    System.out.println(is1.read());//此处会is1不能再使用文件描述符fd了

在上述示例中,文件描述符fd在流 is 和 is1 之间共享使用。如果对 is 进行关闭操作,那么 is1 也会随之关闭(即文件描述符fd会被关闭/释放),这是因为FileDescriptor.class::closeAll()函数会把该文件描述符关联的Closeable对象(其实就是FileInputStream实例、FileOutputStream实例、RandomAccessFile等实例)通通都关闭掉(详细请看标题3.2、closeAll()函数)

参考资料:
https://www.cnblogs.com/yungyu16/p/13053912.html

posted @ 2026-02-06 18:46  Carey_ccl  阅读(2)  评论(0)    收藏  举报