summaryrefslogtreecommitdiffstats
path: root/loader/popen.c
blob: 75a15031f9018459dda373c8256755d576e4e3a4 (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
#include <errno.h>
#include <fcntl.h>
#include <popt.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>

#include <syslog.h>

struct req {
    FILE * f;
    pid_t child;
};

struct req lastRequest = { NULL, -1 };

FILE * popen(const char * command, const char * type) {
    char ** argv;
    int argc;
    int p[2];
    pid_t child;

    if (strcmp(type, "r") || lastRequest.f)
	return NULL;

    if (poptParseArgvString(command, &argc, (const char ***) &argv)) {
	return NULL;
    }

    pipe(p);

    if (!(child = fork())) {
	int i;
	char ** args;

	close(p[0]);
	dup2(p[1], 1);
	dup2(p[1], 2);
	close(p[1]);

	args = malloc(sizeof(*args) * (argc + 1));
	for (i = 0; i < argc; i++) {
	    args[i] = argv[i];
	}

	args[argc] = NULL;

	execv("/sbin/insmod", args);
	exit(1);
    }

    free(argv);

    close(p[1]);

    lastRequest.f = fdopen(p[0], "r");
    lastRequest.child = child;

    return lastRequest.f;
}

int pclose(FILE * stream) {
    int status;

    if (stream != lastRequest.f) return -1;

    fclose(stream);
    
    waitpid(lastRequest.child, &status, 0);
    lastRequest.f = NULL;

    return status;
}