Home | History | Annotate | Line # | Download | only in apply
apply.c revision 1.5
      1 /*	$NetBSD: apply.c,v 1.5 1997/10/18 12:23:21 lukem Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1994
      5  *	The Regents of the University of California.  All rights reserved.
      6  *
      7  * This code is derived from software contributed to Berkeley by
      8  * Jan-Simon Pendry.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *	This product includes software developed by the University of
     21  *	California, Berkeley and its contributors.
     22  * 4. Neither the name of the University nor the names of its contributors
     23  *    may be used to endorse or promote products derived from this software
     24  *    without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     36  * SUCH DAMAGE.
     37  */
     38 
     39 #include <sys/cdefs.h>
     40 #ifndef lint
     41 #if 0
     42 static char sccsid[] = "@(#)apply.c	8.4 (Berkeley) 4/4/94";
     43 #else
     44 __RCSID("$NetBSD: apply.c,v 1.5 1997/10/18 12:23:21 lukem Exp $");
     45 #endif
     46 #endif /* not lint */
     47 
     48 #include <sys/wait.h>
     49 
     50 #include <ctype.h>
     51 #include <err.h>
     52 #include <paths.h>
     53 #include <signal.h>
     54 #include <stdio.h>
     55 #include <stdlib.h>
     56 #include <string.h>
     57 #include <unistd.h>
     58 
     59 int	main __P((int, char **));
     60 void	usage __P((void));
     61 int	system __P((const char *));
     62 
     63 int
     64 main(argc, argv)
     65 	int argc;
     66 	char *argv[];
     67 {
     68 	int ch, clen, debug, i, l, magic, n, nargs, rval;
     69 	char *c, *cmd, *p, *q;
     70 
     71 	debug = 0;
     72 	magic = '%';		/* Default magic char is `%'. */
     73 	nargs = -1;
     74 	while ((ch = getopt(argc, argv, "a:d0123456789")) != -1)
     75 		switch (ch) {
     76 		case 'a':
     77 			if (optarg[1] != '\0')
     78 				errx(1,
     79 				    "illegal magic character specification.");
     80 			magic = optarg[0];
     81 			break;
     82 		case 'd':
     83 			debug = 1;
     84 			break;
     85 		case '0': case '1': case '2': case '3': case '4':
     86 		case '5': case '6': case '7': case '8': case '9':
     87 			if (nargs != -1)
     88 				errx(1,
     89 				    "only one -# argument may be specified.");
     90 			nargs = optopt - '0';
     91 			break;
     92 		default:
     93 			usage();
     94 		}
     95 	argc -= optind;
     96 	argv += optind;
     97 
     98 	if (argc < 2)
     99 		usage();
    100 
    101 	/*
    102 	 * The command to run is argv[0], and the args are argv[1..].
    103 	 * Look for %digit references in the command, remembering the
    104 	 * largest one.
    105 	 */
    106 	for (n = 0, p = argv[0]; *p != '\0'; ++p)
    107 		if (p[0] == magic && isdigit(p[1]) && p[1] != '0') {
    108 			++p;
    109 			if (p[0] - '0' > n)
    110 				n = p[0] - '0';
    111 		}
    112 
    113 	/*
    114 	 * If there were any %digit references, then use those, otherwise
    115 	 * build a new command string with sufficient %digit references at
    116 	 * the end to consume (nargs) arguments each time round the loop.
    117 	 * Allocate enough space to hold the maximum command.
    118 	 */
    119 	if ((cmd = malloc(sizeof("exec ") - 1 +
    120 	    strlen(argv[0]) + 9 * (sizeof(" %1") - 1) + 1)) == NULL)
    121 		err(1, "malloc");
    122 
    123 	if (n == 0) {
    124 		/* If nargs not set, default to a single argument. */
    125 		if (nargs == -1)
    126 			nargs = 1;
    127 
    128 		p = cmd;
    129 		p += sprintf(cmd, "exec %s", argv[0]);
    130 		for (i = 1; i <= nargs; i++)
    131 			p += sprintf(p, " %c%d", magic, i);
    132 
    133 		/*
    134 		 * If nargs set to the special value 0, eat a single
    135 		 * argument for each command execution.
    136 		 */
    137 		if (nargs == 0)
    138 			nargs = 1;
    139 	} else {
    140 		(void)sprintf(cmd, "exec %s", argv[0]);
    141 		nargs = n;
    142 	}
    143 
    144 	/*
    145 	 * Grab some space in which to build the command.  Allocate
    146 	 * as necessary later, but no reason to build it up slowly
    147 	 * for the normal case.
    148 	 */
    149 	if ((c = malloc(clen = 1024)) == NULL)
    150 		err(1, "malloc");
    151 
    152 	/*
    153 	 * (argc) and (argv) are still offset by one to make it simpler to
    154 	 * expand %digit references.  At the end of the loop check for (argc)
    155 	 * equals 1 means that all the (argv) has been consumed.
    156 	 */
    157 	for (rval = 0; argc > nargs; argc -= nargs, argv += nargs) {
    158 		/*
    159 		 * Find a max value for the command length, and ensure
    160 		 * there's enough space to build it.
    161 		 */
    162 		for (l = strlen(cmd), i = 0; i < nargs; i++)
    163 			l += strlen(argv[i]);
    164 		if (l > clen && (c = realloc(c, clen = l)) == NULL)
    165 			err(1, "malloc");
    166 
    167 		/* Expand command argv references. */
    168 		for (p = cmd, q = c; *p != '\0'; ++p)
    169 			if (p[0] == magic && isdigit(p[1]) && p[1] != '0')
    170 				q += sprintf(q, "%s", argv[(++p)[0] - '0']);
    171 			else
    172 				*q++ = *p;
    173 
    174 		/* Terminate the command string. */
    175 		*q = '\0';
    176 
    177 		/* Run the command. */
    178 		if (debug)
    179 			(void)printf("%s\n", c);
    180 		else
    181 			if (system(c))
    182 				rval = 1;
    183 	}
    184 
    185 	if (argc != 1)
    186 		errx(1, "expecting additional argument%s after \"%s\"",
    187 		    (nargs - argc) ? "s" : "", argv[argc - 1]);
    188 	exit(rval);
    189 }
    190 
    191 /*
    192  * system --
    193  * 	Private version of system(3).  Use the user's SHELL environment
    194  *	variable as the shell to execute.
    195  */
    196 int
    197 system(command)
    198 	const char *command;
    199 {
    200 	static char *name, *shell;
    201 	union wait pstat;
    202 	pid_t pid;
    203 	int omask;
    204 	sig_t intsave, quitsave;
    205 
    206 	if (shell == NULL) {
    207 		if ((shell = getenv("SHELL")) == NULL)
    208 			shell = _PATH_BSHELL;
    209 		if ((name = strrchr(shell, '/')) == NULL)
    210 			name = shell;
    211 		else
    212 			++name;
    213 	}
    214 	if (!command)		/* just checking... */
    215 		return(1);
    216 
    217 	omask = sigblock(sigmask(SIGCHLD));
    218 	switch(pid = vfork()) {
    219 	case -1:			/* error */
    220 		err(1, "fork");
    221 	case 0:				/* child */
    222 		(void)sigsetmask(omask);
    223 		execl(shell, name, "-c", command, NULL);
    224 		err(1, "%s", shell);
    225 	}
    226 	intsave = signal(SIGINT, SIG_IGN);
    227 	quitsave = signal(SIGQUIT, SIG_IGN);
    228 	pid = waitpid(pid, (int *)&pstat, 0);
    229 	(void)sigsetmask(omask);
    230 	(void)signal(SIGINT, intsave);
    231 	(void)signal(SIGQUIT, quitsave);
    232 	return(pid == -1 ? -1 : pstat.w_status);
    233 }
    234 
    235 void
    236 usage()
    237 {
    238 
    239 	(void)fprintf(stderr,
    240 	    "usage: apply [-a magic] [-0123456789] command arguments ...\n");
    241 	exit(1);
    242 }
    243