Initial import from FreeBSD RELENG_4:
[games.git] / usr.sbin / pkg_install / lib / exec.c
1 /*
2  * FreeBSD install - a package for the installation and maintainance
3  * of non-core utilities.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * Jordan K. Hubbard
15  * 18 July 1993
16  *
17  * Miscellaneous system routines.
18  *
19  */
20
21 #include <sys/cdefs.h>
22 __FBSDID("$FreeBSD: src/usr.sbin/pkg_install/lib/exec.c,v 1.7.2.3 2002/08/20 06:35:08 obrien Exp $");
23
24 #include "lib.h"
25 #include <err.h>
26
27 /*
28  * Unusual system() substitute.  Accepts format string and args,
29  * builds and executes command.  Returns exit code.
30  */
31
32 int
33 vsystem(const char *fmt, ...)
34 {
35     va_list args;
36     char *cmd;
37     int ret, maxargs;
38
39     maxargs = sysconf(_SC_ARG_MAX);
40     maxargs -= 32;                      /* some slop for the sh -c */
41     cmd = malloc(maxargs);
42     if (!cmd) {
43         warnx("vsystem can't alloc arg space");
44         return 1;
45     }
46
47     va_start(args, fmt);
48     if (vsnprintf(cmd, maxargs, fmt, args) > maxargs) {
49         warnx("vsystem args are too long");
50         return 1;
51     }
52 #ifdef DEBUG
53 printf("Executing %s\n", cmd);
54 #endif
55     ret = system(cmd);
56     va_end(args);
57     free(cmd);
58     return ret;
59 }
60
61 char *
62 vpipe(const char *fmt, ...)
63 {
64    FILE *fp;
65    char *cmd, *rp;
66    int maxargs;
67    va_list args;
68
69     rp = malloc(MAXPATHLEN);
70     if (!rp) {
71         warnx("vpipe can't alloc buffer space");
72         return NULL;
73     }
74     maxargs = sysconf(_SC_ARG_MAX);
75     maxargs -= 32;                          /* some slop for the sh -c */
76     cmd = alloca(maxargs);
77     if (!cmd) {
78         warnx("vpipe can't alloc arg space");
79         return NULL;
80     }
81
82     va_start(args, fmt);
83     if (vsnprintf(cmd, maxargs, fmt, args) > maxargs) {
84         warnx("vsystem args are too long");
85         return NULL;
86     }
87 #ifdef DEBUG
88     fprintf(stderr, "Executing %s\n", cmd);
89 #endif
90     fflush(NULL);
91     fp = popen(cmd, "r");
92     if (fp == NULL) {
93         warnx("popen() failed");
94         return NULL;
95     }
96     get_string(rp, MAXPATHLEN, fp);
97 #ifdef DEBUG
98     fprintf(stderr, "Returned %s\n", rp);
99 #endif
100     va_end(args);
101     if (pclose(fp) || (strlen(rp) == 0)) {
102         free(rp);
103         return NULL;
104     }
105     return rp;
106 }