Calling External Programs with EXEC
#include <unistd.h>
#include <sys/wait.h>
#include <stdio.h>
main()
{
     char *arglist[]  = { "cp", "a", "b", NULL}, *cp_command = "/bin/cp";
     pid_t pid;
     int status;
   
     if ((pid = fork()) < 0)
     {
          perror("Bad fork!\n");
          exit(1);
     }
     if (pid != 0)   /* Parent */
     {
          wait(&status);
          system("ls -l b");    /* Overhead for "system" higher than execs!! */
          system("cat b");
     }
     else
     {
          execvp(cp_command, arglist);
     }
}
/****************** SAMPLE EXECUTION OF ABOVE CODE ****************************/
-rw-------  1 perry          15 Apr 26 17:23 b

Contents of file "a":

This is file a

/**************************  Demonstration of calling  ***********************/
/**************************  an unrelated program from ***********************/
/**************************  from a slave child.       ***********************/
#include <unistd.h>
#include <sys/wait.h>
#include <stdio.h>
main(int argc, char *argv[])
{
     pid_t pid;
     char *arglist[] = { "environ", NULL }; 
     int status;
   
     if ((pid = fork()) < 0)
     {
           perror("Fork failed!\n");
           exit(1);
     }
     if (pid != 0)   /* Parent */
     {
           wait(&status);
           printf("Back from exec.\n");
     }
     else
     {
           execvp("/usr/users/perry/sysprog/environ", arglist);
     }
}
/******************* SAMPLE EXECUTION OF ABOVE CODE *************************/

_=a.out
LANG=C
HZ=100
VISUAL=/usr/bin/emacs
PATH=/usr/local/bin:/usr/sbin:/usr/bsd:/sbin:/usr/bin:/bin:/usr/bin/X11:.:/home/staff/staff2/jwp2286/bin:/usr/bin:/usr/local/tutor:/usr/bsd:/usr/local/bin:/usr/etc
NOMSGLABEL=1
REMOTEUSER=UNKNOWN
EDITOR=/usr/bin/emacs
LOGNAME=jwp2286
MAIL=/usr/mail/jwp2286
USER=jwp2286
history=20
MSGVERB=text:action
SHELL=/bin/ksh
REMOTEHOST=153.18.8.18
HOME=/home/staff/staff2/jwp2286
TERM=vt100
savehist=20
PWD=/home/staff/staff2/jwp2286/sysprog
TZ=PST8PDT
ENV=~jwp2286/.kshrc
NOMSGSEVERITY=1
Back from exec.
/**********************  Creating your own environment.  *********************/
#include <unistd.h>
#include <sys/wait.h>
#include <stdio.h>
main(int argc, char *argv[])
{
     pid_t pid;
     char *arglist[] = { "environ", NULL };
     char *envp[] = { "foo", "bar", "snafu", NULL };
     int status;
   
     if ((pid = fork()) < 0)
     {
          perror("Fork failed!\n");
          exit(1);
     }
     if (pid != 0)   /* Parent */
     {
          wait(&status);
          printf("Back from exec.\n");
     }
     else execve("/usr/users/perry/sysprog/environ", arglist, envp); 
}
/******************* SAMPLE EXECUTION OF ABOVE CODE ************************/
foo
bar
snafu
Back from exec.
/**********************  PROGRAM ENVIRON ***********************************/
#include <stdio.h>
main(int argc, char *argv[], char *envp[])
{
       while ( *envp  ) printf("%s\n", *envp++);
}