Useful POSIX Recipes

Last updated on 2015-04-25 12:09:48 -0300

1. Spawn Process (a.k.a. fork-exec)

http://en.wikipedia.org/wiki/Fork_(system_call)

#include <unistd.h>

void
spawn(char *const argv[])
{
    pid_t pid;
    int status;

    pid = fork();
    if (pid > 0) {
        /* fork() succeeded. */
        waitpid(pid, &status, 0);
    } else if (pid == 0) {
        /* Child process. */
        execvp(argv[0], argv);
    }
}

2. Read Output of Child Process

http://stackoverflow.com/questions/2605130/redirecting-exec-output-to-a-buffer-or-file

int pipefd[2];
pipe(pipefd);

if (fork() == 0) {
    close(pipefd[0]);    /* close reading end in the child */
    dup2(pipefd[1], 1);  /* send stdout to the pipe */
    dup2(pipefd[1], 2);  /* send stderr to the pipe */
    close(pipefd[1]);    /* this descriptor is no longer needed */
    exec(...);
} else {
    char buffer[1024];

    close(pipefd[1]);  /* close the write end of the pipe in the parent */
    while (read(pipefd[0], buffer, sizeof(buffer)) != 0) {
        ...
    }
}

3. List Directory

#include <stdio.h>
#include <dirent.h>

int
ls(const char *path)
{
    DIR *dp;
    struct dirent *ep;

    if(!(dp = opendir(path)))
        return -1;
    while ((ep = readdir(dp)))
        puts(ep->d_name);
    closedir(dp);
    return 0;
}