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

int main(int argc, char *argv[]) {
    int use_cloexec = argc > 1;

    int fd = open("example.txt", O_CREAT | O_WRONLY | O_TRUNC, 0644);
    if (fd == -1) {
        perror("open");
        return 1;
    }

    printf("main: opened example.txt as fd %d\n", fd);

    if (use_cloexec) {
        int flags = fcntl(fd, F_GETFD);
        if (flags == -1) {
            perror("fcntl F_GETFD");
            return 1;
        }

        if (fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == -1) {
            perror("fcntl F_SETFD");
            return 1;
        }

        printf("main: set FD_CLOEXEC on fd %d\n", fd);
    } else {
        printf("main: did NOT set FD_CLOEXEC on fd %d\n", fd);
    }

    char fd_as_string[32];
    snprintf(fd_as_string, sizeof(fd_as_string), "%d", fd);

    execl("./checkfd", "./checkfd", fd_as_string, NULL);

    perror("execl");
    return 1;
}
