static int close_all_fds_using_parsing()

in native/exec_pty.c [70:101]


static int close_all_fds_using_parsing(unsigned int from_fd_inclusive) {
    // If `opendir` is implemented using a file descriptor, we may close it accidentally.
    // Let's close a few lowest file descriptors, in hope that `opendir` will use it.
    int lowest_fds_to_close = 2;
    for (int i = 0; i < lowest_fds_to_close; i++) {
        close(from_fd_inclusive + i);
    }

#if defined(__APPLE__)
#define FD_DIR "/dev/fd"
#else
#define FD_DIR "/proc/self/fd"
#endif

    DIR *dirp = opendir(FD_DIR);
    if (dirp == NULL) return -1;

    struct dirent *direntp;

    while ((direntp = readdir(dirp)) != NULL) {
        if (isdigit(direntp->d_name[0])) {
            int fd = strtol(direntp->d_name, NULL, 10);
            if (fd >= from_fd_inclusive + lowest_fds_to_close && fd != dirfd(dirp)) {
                close(fd);
            }
        }
    }

    closedir(dirp);

    return 0;
}