/*
 * Copyright (c) 2005, 2011 Kamo Hiroyasu
 *
 * Permission to use, copy, modify, and distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

/*
 *  call 'pwd' command and then call `ls' command
 *  Author: Kamo Hiroyasu <wd@ics.nara-wu.ac.jp>
 */

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

void	call_command(const char *const *, char *const *);

static const char	*const pwd_paths[] = {
	"/bin/pwd", "/usr/bin/pwd", NULL
};
static const char	*const ls_paths[] = {
	"/bin/ls", "/usr/bin/ls", NULL
};
static char	*const pwd_args[] = {"pwd", NULL};
static char	*const ls_args[] = {"ls", "-l", NULL};

void
call_command(const char *const paths[], char *const argv[])
{
	size_t		i;
	pid_t		pid;
	int		status;

	if ((pid = fork()) == 0) {
		for (i = 0; paths[i] != NULL; i ++) {
			execv(paths[i], argv);
		}
		_exit(1);
	}
	if (pid == -1) {
		perror(NULL);
		exit(1);
	}
	waitpid(pid, &status, 0);
	if (!WIFEXITED(status) || WEXITSTATUS(status) != 0) {
		fprintf(stderr, "%s failed\n", argv[0]);
		exit(1);
	}
}

int
main(int argc, char *argv[])
{
	call_command(pwd_paths, pwd_args);
	call_command(ls_paths, ls_args);
	return 0;
}
