/*
20140410
Jan Mojzis
Public domain.
*/

#include <signal.h>
#include <unistd.h>
#include "run.h"
#include "fail.h"
#include "open.h"

static void cat(void) {
    char *catcmd[2] = { (char *)"cat", 0 };
    execvp(*catcmd, catcmd);
}

/* test if close-on-exec works for open_read() */
static void test1(void) {

    int fd;

    close(0);
    fd = open_read("opentest.c");
    if (fd != 0) fail("unable to open opentest.c for reading");
    cat();
}

/* test if close-on-exec works for open_write() */
static void test2(void) {

    int fd;

    close(1);
    fd = open_write("opentest.data");
    if (fd != 1) fail("unable to open opentest.data for writing");
    cat();
}

/* test if close-on-exec works for open_pipe() */
static void test3(void) {

    int fd, pi[2];

    close(0);
    close(1);
    fd = open_pipe(pi);
    if (fd == -1) fail("unable to open pipe");
    if (pi[0] != 0) fail("unable to open pipe");
    if (pi[1] != 1) fail("unable to open pipe");
    cat();
}

/* dummy test */
static void testdummy(void) {
    _exit(0);
}

int main(void) {
    alarm(10);
    run_mustfail(test1);
    run_mustfail(test2);
    run_mustfail(test3);
    run_mustpass(testdummy);
    _exit(0);
}
