/*
 * Exercise 3-8 
 */

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

#define MAX 256
#define CMD_MAX 10

char *valid_cmds=" ls  ps  df ";
int main()
{
	char line_input[MAX], the_cmd[CMD_MAX];
	char *new_args[CMD_MAX], *cp;
	int i;
	int child_wait_status;
	while(1)
	{
		printf("cmd> ");
		if(gets(line_input) != NULL)
		{
			cp=line_input;
			i=0;
			if((new_args[i]=strtok(cp, " ")) != NULL)
			{
				sprintf(the_cmd, "%s ", new_args[i]);
				if((strstr(valid_cmds, the_cmd) - valid_cmds) % 4 == 1)
				{
					do
					{
						++i;
						cp=NULL;
						new_args[i]=strtok(cp, " ");
					} while(i<CMD_MAX-1 && new_args[i] != NULL);

					new_args[i]=NULL;
					switch(fork())
					{
						case 0:
							execvp(new_args[0], new_args);
							perror("execvp failure");
							exit(1);
						case -1:
							perror("fork failure");
							break;
						default:
							wait(&child_wait_status);
					}
				}
				else
					printf("huh?\n");
			}
		}
	}
}
