/*
** execprog.c -- invoke an external command synchronously
**               This is a safer alternative to system(3)
*/

#include <h/mh.h>
#include <unistd.h>
#include <stdarg.h>
#include <sysexits.h>


int
execprog(char *cmd, char **arg)
{
	pid_t pid;

	fflush(stdout);
	switch (pid = fork()) {
	case -1:
		/* fork error */
		advise("fork", "unable to");
		return -1;

	case 0:
		/* child */
		execvp(cmd, arg);
		fprintf(stderr, "unable to exec ");
		perror(cmd);
		_exit(EX_OSERR);

	default:
		/* parent */
		return pidXwait(pid, cmd);
	}

	return -1;  /* NOT REACHED */
}


int
execprogl(char *cmd, char *arg, ...)
{
	va_list ap;
	int argc = 0;
	char *argv[MAXARGS];
	char *cp;
	int ret;

	argv[argc++] = mhbasename(arg);
	va_start(ap, arg);
	while ((cp = va_arg(ap, char *))) {
		argv[argc++] = cp;
	}
	argv[argc] = NULL;
	ret = execprog(cmd, argv);
	va_end(ap);

	return ret;
}
