Sobes.tech
Middle

Can one inode have multiple file descriptors?

sobes.tech AI

Answer from AI

Yes, one inode can have multiple file descriptors. In Unix-like systems, an inode is a data structure that stores information about a file, and a file descriptor is an integer identifier used by a process to access an open file.

Multiple file descriptors can point to the same inode, for example, if one process opens a file multiple times, or if different processes open the same file. Additionally, if a file has multiple hard links, all of them point to the same inode, and opening the file through any of these links will create a file descriptor associated with that inode.

Here's an example in C showing that two file descriptors can point to the same inode:

#include <stdio.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>

int main() {
    int fd1 = open("file.txt", O_RDONLY);
    int fd2 = open("file.txt", O_RDONLY);

    struct stat stat1, stat2;
    fstat(fd1, &stat1);
    fstat(fd2, &stat2);

    printf("Inode fd1: %ld\n", (long)stat1.st_ino);
    printf("Inode fd2: %ld\n", (long)stat2.st_ino);

    close(fd1);
    close(fd2);
    return 0;
}

The output will show the same inode for both descriptors.