summaryrefslogtreecommitdiff
path: root/rf.c
blob: 64489e4d1baac960febdee72c1e64ca61532dda2 (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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/*
 *  runfile - rf
 *
 *  a no-dependancy, minimal
 *  POSIX C99 Make/justfile
 *  alternative to run commands.
 *
 *             czjstmax
 *   <jstmaxlol at
 *      disroot dot org>
 */

#define _POSIX_C_SOURCE 200809L

#define RUNFILE_VERSION 1

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

void usage();

int main(int argc, char **argv)
{
    if (argc > 2)
        usage();
    else if (argc >= 2) {
        for (int i = 1; i < argc; i++) {
            if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0)
                usage();
        }

    }

    FILE *f = fopen("rfile", "r");

    if (!f) {
        printf("no rfile found.\n");
        return 1;
    }

    wordexp_t p;
    char *line = NULL;
    size_t len = 0;

    while (getline(&line, &len, f) != -1) {
        line[strcspn(line, "\n")] = '\0';
        printf("$ %s\n", line);

        wordexp(line, &p, 0);

        pid_t pid = fork();

        if (pid == 0) {
            execvp(p.we_wordv[0], p.we_wordv);

            perror("failed to run command");
            wordfree(&p);
            free(line);
            fclose(f);
            _exit(1);
        }
        else if (pid > 0) {
            int status;
            waitpid(pid, &status, 0);
        }
        else {
            perror("fork failed");
            return 1;
        }
    }

    wordfree(&p);
    free(line);
    fclose(f);
    return 0;
}

void usage()
{
    printf(
        "< runfile usage >\n"
        "syn: rf [section]\n"
    );
}