mikaku / Fiwix

A UNIX-like kernel for the i386 architecture
https://www.fiwix.org
Other
407 stars 32 forks source link

Support F_DUPFD_CLOEXEC for fcntl #40

Closed rick-masters closed 1 year ago

rick-masters commented 1 year ago

Please support F_DUPFD_CLOEXEC for fcntl.

It is used by musl-1.1.24 library (which is used by live-bootstrap) to implement popen: https://git.musl-libc.org/cgit/musl/tree/src/stdio/popen.c?h=v1.1.24&id=ea9525c8bcf6170df59364c4bcd616de1acf8703

Here is a test program fdcloexec.c:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>

#ifndef F_DUPFD_CLOEXEC
#define F_DUPFD_CLOEXEC        1030    /* duplicate file descriptor with close-on-exec*/
#endif

int main() {
        char cmd[100];

        int myfile = open("mytestfile", O_WRONLY | O_CREAT);
        int mydupfd = fcntl(myfile, F_DUPFD_CLOEXEC);
        //int mydupfd = fcntl(myfile, F_DUPFD);

        printf("mydupfd = %d\n", mydupfd);
        sprintf(cmd, "./checkfd %d", mydupfd);
        system(cmd);
}

Here is the second test program checkfd.c:

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv) {
        if  (argc < 2) {
                exit(1);
        }
        int result = lseek(atoi(argv[1]), 0, SEEK_SET);
        printf("checkfd result = %d\n", result);
}

To test:

# cc fdcloexec.c -o fdcloexec
# cc checkfd.c -o checkfd
# ./fdcloexec
mydupfd = 4
checkfd result = -1

The first program opens a file and passes that file number as an argument to the checkfd program which it executes with system.

If F_DUPFD_CLOEXEC is used to duplicate the file number then the checkfd result should be -1. This indicates the file number passed to checkfd was closed when the program checkfd was executed.

If a plain F_DUPFD is used the checkfd result will be 0.

A PR is forthcoming which implements the F_DUPFD_CLOEXEC option.

mikaku commented 1 year ago

Looks good to me. Thank you.