// testexec.cpp

// This program demonstrates the use of execl() to read
// command lines from stdin and execute them in a child
// shell program (just like the Bourne shell: /bin/sh).

// Author: Dr. Jeff Blessing
// Date:   November 28, 2000

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <iostream>
using namespace std;


int System(const char *cmd) 	// emulate the Unix system function
{
   pid_t pid;
   int	 status;

   switch (pid = fork()) 
   {
      case -1:	return -1;	// fork failed!
      case  0:	execl("/bin/sh", "sh", "-c", cmd, NULL);
		perror("execl");
		exit(errno);
   }
   if (waitpid(pid, &status, 0) == pid && WIFEXITED(status))
      return WEXITSTATUS(status);

   return -1;		// child shell exited abnormally!
}


int main() 
{
   int 	rc = 0;
   const int bufsize = 256;
   char	buf[bufsize];

   do
   {
      printf("sh> ");
      fflush(stdout);
      if (!fgets(buf, bufsize, stdin)) break;	// stop on ctrl-D (EOF)
      rc = System(buf);
   } while (!rc);

   return rc;
}
