#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>

static void terminate(const char *msg, int code)
{
    perror(msg);
    exit(code);
}

int main(int argc, char **argv)
{
    int fd, pid, status;

    if (argc != 2) {
        fprintf(stderr, "Usage: %s <file name>\n", argv[0]);
        return 1;
    }

    pid = fork();
    if (pid == -1)
        terminate("pid", 2);

    if (pid == 0) {
        fd = open(argv[1], O_WRONLY|O_CREAT|O_TRUNC, 0666);
        if (fd == -1)
            terminate("open", 2);
        dup2(fd, 1);
        close(fd);
        execlp("ls", "ls", "-l", "-a", "-R", "./", NULL);
        terminate("ls", 2);
    }

    wait(&status);
    if (!WIFEXITED(status) || WEXITSTATUS(status) != 0)
        terminate("wait", 2);

    return 0;
}
