CS 466 - Operating Systems - Spring 2008
System Calls for Process Creation


Loyola College > Department of Computer Science > Dr. James Glenn > CS 466 > Examples and Lecture Notes > System Calls for Process Creation

fork.c

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

/**
 * Creates a child process.
 */

int main(int argc, char **argv)
{
  // child process gets a copy of parent's data

  int x = 1;

  pid_t pid = fork();

  if (pid == 0) // child gets 0 returned from fork; parent gets child's id
    {
      x = 2; // this change will not be visible to parent
      printf("Child: x=%d\n", x);
    }
  else
    {
      printf("Parent: x=%d\n", x);
    }      
}

execvp.c

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

int main(int argc, char **argv)
{
  char *ls_args[] = {"ls", "-l", NULL};
  execvp("ls", ls_args);

  // process terminates when ls terminates; we only get here if there was
  // a problem loading the new code

  fprintf(stderr, "Could not execute ls\n");
}

pipe.c

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

/**
 * Uses a pipe to send a message from a child process to its parent.
 */

int main(int argc, char **argv)
{
  // must create pipe before fork so both processes share it

  int pipe_fds[2];
  pipe(pipe_fds);

  // create child process

  pid_t pid = fork();

  if (pid == 0)
    {
      // child process gets here

      // write message to pipe

      char *message = "hi";
      write(pipe_fds[1], message, 3);

      // terminate with status 1

      return 1;
    }
  else
    {
      // close unused end of pipe -- without this, the read system call
      // doesn't know that the 3 bytes sent are all that will come, so
      // it will hang waiting for the 80 byte request to be satisfied

      close(pipe_fds[1]);

      // receive message

      char message[80];
      read(pipe_fds[0], message, 80);

      printf("Message from child: %s\n", message);

      // wait for child to terminate and get its status
      
      int status;
      int term_id = wait(&status);
      printf("Child (id = %d) terminated, status %d\n", term_id, WEXITSTATUS(status));
    }      
}
This code can also be downloaded from the files fork.c, execvp.c, and pipe.c.