Lab 1: Process Control
Jan. 10/11, 2007
[153 Home]      [Introduction]      [What to do in lab?]      [Resources]

Introduction
The fork() system call creates a new process that is a copy of the calling process, except that it has its own copy of the memory, its own process ID, and its own pointers to shared kernel entities. After fork() has been called, two processes will execute the next statement after the fork() in their own address spaces: the parent and the child. If the call succeeds, then in the parent process, fork() returns the process ID of the newly created child process and in the child process, fork returns zero.

The exec() family of system calls changes the program that a process is currently executing. For example, execve() has the form

        int execve(const char *path, char *const argv[], char *const envp[]);

The path argument is the pathname of a file that contains the new program to be executed. The argv array is a list of parameter strings, and the envp array is a list of environment variable strings and values. When a process encounters the execve() system call, the next instruction it executes will be the one at the entry point of the new executable file.

The wait() system call is used by a process to block itself until the kernel signals the process to execute again, for example because one of its child processes has terminated.



What to do in lab?
  1. Write a program that spawns a child process: the parent process prints its own PID and its child's PID, while the child process prints its own PID and its parent's PID.
    Hint: You'll need to use fork(), getpid() and getppid().

  2. Add two integer variables to the program, one is global, another is on the stack. In the child process, increment both variables. At the end, both processes need to print the value of these two variables.
    Hint: Local variables inside a function, if not declared as static, are usually allocated on the stack.

  3. In the above program, let the child process sleep for 2 seconds before it prints the variable values. Then let the parent prints the values only after its child process terminates.
    Hint: Use wait() to block the parent process.

  4. In stead of running the same program in the child process, let it run a new program. For example, let the child process print the current directory.
    Hint: Use pwd to get the current directory, and use one of the exec() system calls to change the program that the child process is currently executing.

Resources
  1. Lab manual: p.27-29, p.71-72
  2. man -a fork
  3. man -a exec
  4. man -a wait