aboutsummaryrefslogtreecommitdiff
path: root/subproc.c
blob: ae4991f6fd41eded44f2fbb3c9268bf30945d18a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <stddef.h>
#include <stdarg.h>
#include <string.h>
#include <err.h>

#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

#include "subproc.h"

void system_argv_array(char **args)
{
    pid_t pid = fork();
    if (pid < 0)
        err(1, "fork");

    if (pid == 0) {
        execvp(args[0], args);
        warn("execvp");
        _exit(127);
    }

    int status;
    if (waitpid(pid, &status, 0) != pid)
        err(1, "waitpid");
    if (!(WIFEXITED(status) && WEXITSTATUS(status) == 0))
        errx(1, "subcommand failed");
}

void system_argv(const char *cmd, ...)
{
    int nargs, nchars;
    const char *word;
    va_list ap;

    va_start(ap, cmd);
    nargs = 1;                         /* terminating NULL */
    nchars = 0;
    for (word = cmd; word; word = va_arg(ap, const char *)) {
        nargs++;
        nchars += 1 + strlen(word);
    }
    va_end(ap);

    char *args[nargs], chars[nchars];
    char **argp = args, *charp = chars;
    va_start(ap, cmd);
    for (word = cmd; word; word = va_arg(ap, const char *)) {
        *argp++ = charp;
        strcpy(charp, word);
        charp += 1 + strlen(word);
    }
    va_end(ap);
    *argp++ = NULL;

    system_argv_array(args);
}