/*
* Simple program to demonstrate the fork/exec/run sequence for creating
* processes in Unix.
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
int main()
{
/* Ask for a program to run. This is just the file name of an
executable. */
printf("What shall I run? ");
char buf[1000];
fgets(buf, sizeof buf, stdin);
buf[strlen(buf)-1] = '\0'; // Lose \n.
/* Request a single parameter. */
printf("Would you like a parameter for that? (return for none) ");
char parm[1000];
fgets(parm, sizeof parm, stdin);
parm[strlen(parm)-1] = '\0'; // Lose \n.
/* Create a child process and try to run the program in it. */
if(fork() == 0) {
if(strlen(parm) > 0)
execl(buf, buf, parm, 0);
else
execl(buf, buf, 0);
printf("Sorry, the exec failed.\n");
exit(1);
}
/* See what was the cause of the child processes' demise. */
int status;
wait(&status);
if(WIFEXITED(status)) printf("Exited.\n");
else if(WIFSIGNALED(status)) printf("Killed.\n");
else printf("Mysteriously vanished.\n");
}
/*
* Note: This program really should check the return values for fork() and for
* exec() to make sure they succeeded, and print an error message if not.
* Failure is indicated by a negative return value. It would also help to use
* errno and strerror() to print a descriptive error message in place of the
* existing exec() failure message, or for the new messages.
*
* It also uses uses gets() and fixed-size buffers, which creates a risk of
* buffer overflow.
*/