Example

This example shows both the list and vector versions of the exec function. (exec2.c)

#include <stdio.h>  /* printf, stdout */
#include <stdlib.h> /* exit           */
#include <unistd.h> /* fork, getpid   */
#include <wait.h>   /* wait           */
#include <errno.h>  /* perror         */

int main(int argc, char **argv)
{
  int pid;
  int use_list = 1;

    /* If any args were given, use vector */
  if (argc > 1)
    use_list = 0;

   pid = fork();

  if (pid == 0) /* child */
  {
    if (use_list)
    {
      printf("[%i] child: executing a program...\n", getpid());
      /*       executable        0        1          2         3          */
      execl("/usr/bin/geany", "geany", "exec.c", "child.c", "pipe0.c", NULL);
    }
    else /* use vector */
    {
      /*                 0         1         2      */
      char *args[] = {"geany", "exec.c", "pipe1.c", NULL};

      printf("[%i] child: executing a program...\n", getpid());
      execv("/usr/bin/geany", args);
    }

    printf("child: if you see this, the exec failed, errno: %i\n", errno);
    perror("geany");
    exit(10); /* arbitrary exit code */
  }
  else /* parent */
  {
    int code, status;

    printf("parent: waiting for child to terminate\n");
    wait(&status);
    printf("parent: child terminated with value %08X, %i\n", status, status); /* raw value */

    code = WEXITSTATUS(status); /* extract exit code */

    if (WIFEXITED(status)) /* normal exit */
      printf("parent: child terminated normally with exit code %i\n", code);
    else /* abnormal exit */
      printf("parent: child terminated abnormally, code: %i\n", code);
  }

  return 0;
}
Output: (normal exit)
parent: waiting for child to terminate
[32428] child: executing a program...
parent: child terminated with value 0
Output: (abnormal exit)
parent: waiting for child to terminate
[32360] child: executing a program...
parent: child terminated with value 00000009, 9
parent: child terminated abnormally, code: 0
Changing /usr/bin/geany to /usr/bin/foobar and perror("geany") to perror("foobar")
Output:
parent: waiting for child to terminate
[32473] child: executing a program...
child: if you see this, the exec failed, errno: 2
foobar: No such file or directory
parent: child terminated with value 00000A00, 2560
parent: child terminated normally with exit code 10