exec.c revision 252635
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: stable/9/usr.sbin/pkg_install/lib/exec.c 252635 2013-07-03 22:25:00Z obrien $");
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
32int
33vsystem(const char *fmt, ...)
34{
35    va_list args;
36    char *cmd;
37    long maxargs;
38    int ret;
39
40    maxargs = sysconf(_SC_ARG_MAX);
41    maxargs -= 32;			/* some slop for the sh -c */
42    cmd = malloc(maxargs);
43    if (!cmd) {
44	warnx("vsystem can't alloc arg space");
45	return 1;
46    }
47
48    va_start(args, fmt);
49    if (vsnprintf(cmd, maxargs, fmt, args) > maxargs) {
50	warnx("vsystem args are too long");
51	return 1;
52    }
53#ifdef DEBUG
54printf("Executing %s\n", cmd);
55#endif
56    ret = system(cmd);
57    va_end(args);
58    free(cmd);
59    return ret;
60}
61
62char *
63vpipe(const char *fmt, ...)
64{
65   FILE *fp;
66   char *cmd, *rp;
67   int maxargs;
68   va_list args;
69
70    rp = malloc(MAXPATHLEN);
71    if (!rp) {
72	warnx("vpipe can't alloc buffer space");
73	return NULL;
74    }
75    maxargs = sysconf(_SC_ARG_MAX);
76    maxargs -= 32;			    /* some slop for the sh -c */
77    cmd = alloca(maxargs);
78    if (!cmd) {
79	warnx("vpipe can't alloc arg space");
80	return NULL;
81    }
82
83    va_start(args, fmt);
84    if (vsnprintf(cmd, maxargs, fmt, args) > maxargs) {
85	warnx("vsystem args are too long");
86	return NULL;
87    }
88#ifdef DEBUG
89    fprintf(stderr, "Executing %s\n", cmd);
90#endif
91    fflush(NULL);
92    fp = popen(cmd, "r");
93    if (fp == NULL) {
94	warnx("popen() failed");
95	return NULL;
96    }
97    get_string(rp, MAXPATHLEN, fp);
98#ifdef DEBUG
99    fprintf(stderr, "Returned %s\n", rp);
100#endif
101    va_end(args);
102    if (pclose(fp) || (strlen(rp) == 0)) {
103	free(rp);
104	return NULL;
105    }
106    return rp;
107}
108