105 lines
2.4 KiB
C
105 lines
2.4 KiB
C
#ifndef DONT_USE_SYSTEM_SYSEXITS
|
|
# include <sysexits.h>
|
|
#else
|
|
# include "../include/sysexits.h"
|
|
#endif /* ifndef DONT_USE_SYSTEM_SYSEXITS */
|
|
|
|
#include <stdio.h>
|
|
#include <sys/wait.h>
|
|
#include <unistd.h>
|
|
|
|
static char *program_name = "pscat";
|
|
|
|
/* Originally designed to use parentheses but changed to brackets to escape the
|
|
* hassle of escaping them from the Bourne shell. */
|
|
#ifndef USE_ASCII_H
|
|
# define L_PAREN '['
|
|
# define R_PAREN ']'
|
|
#else
|
|
# include "../include/ascii.h"
|
|
# define L_PAREN ASCII_LEFT_SQUARE_BRACKET
|
|
# define R_PAREN ASCII_RIGHT_SQUARE_BRACKET
|
|
#endif /* ifndef USE_ASCII_H */
|
|
|
|
/* Test string containing { c, '\0' } without iteration.
|
|
* Theoretically saves a little bit of time compared to strcmp(3). */
|
|
#define SCMPFLAT(a, b) (*(a) != '\0' && *((a)+1) == '\0' && *(a) == (b))
|
|
|
|
/* Verifies arguments to pscat are sensible. */
|
|
static int
|
|
check_arg(char **argv){
|
|
enum {
|
|
UNINITIALIZED = 0,
|
|
NORMAL = 1,
|
|
INLPAREN = 2
|
|
} s;
|
|
int terms;
|
|
|
|
for(s = UNINITIALIZED, terms = 0; *argv != NULL; ++argv)
|
|
switch(s){
|
|
case UNINITIALIZED: case NORMAL:
|
|
if(SCMPFLAT(*argv, L_PAREN))
|
|
s = INLPAREN;
|
|
else
|
|
return 0; /* syntax error */
|
|
break;
|
|
default: /* >= INLPAREN */
|
|
if(argv[0][1] == '\0'){
|
|
s -= (argv[0][0] == R_PAREN);
|
|
terms += (argv[0][0] == R_PAREN && s == NORMAL);
|
|
s += (argv[0][0] == L_PAREN);
|
|
}
|
|
break;
|
|
}
|
|
|
|
return terms;
|
|
}
|
|
|
|
int main(int argc, char *argv[]){
|
|
char **psstart;
|
|
int child;
|
|
int i;
|
|
int p;
|
|
int retval;
|
|
int terms;
|
|
|
|
retval = 0;
|
|
|
|
if((terms = check_arg(++argv)) == 0){
|
|
fprintf(stderr,
|
|
"Usage: %s \"[\" [utility [argument...]] \"]\" ...\n",
|
|
argv[0] == NULL ? program_name : argv[0]
|
|
);
|
|
return EX_USAGE;
|
|
}
|
|
|
|
/* loop starts with *argv -> the next L_PAREN */
|
|
for(i = 0; i < terms; ++i){
|
|
psstart = ++argv;
|
|
p = 1;
|
|
while(p > 0){
|
|
++argv;
|
|
/* branching here potentially saves a comparison.
|
|
* this seems like the most optimal way to do this,
|
|
* maybe it isn't, i don't care too much */
|
|
if(SCMPFLAT(*argv, L_PAREN))
|
|
++p;
|
|
else if(SCMPFLAT(*argv, R_PAREN))
|
|
--p;
|
|
}
|
|
/* *argv -> the corresponding R_PAREN. turn it into NULL to
|
|
* terminate the argument list to send to execvp(3) */
|
|
*argv = NULL;
|
|
if(fork() == 0){
|
|
execvp(psstart[0], psstart);
|
|
}else
|
|
wait(&child);
|
|
/* interpret status information from wait(2) */
|
|
if(WIFEXITED(child))
|
|
retval += WEXITSTATUS(child);
|
|
++argv;
|
|
}
|
|
|
|
return retval;
|
|
}
|