lab4 Process
  • Introduction
  • Knowing about process
    • Checking System Process
    • Process Identification
  • Let's Fork! Process Creation
    • Background of Process Creation
    • fork system call
    • Distinguish Parent and Child Process
    • Exercises
  • Process Execution
    • First exec example
    • Environment Variables
    • exec Family
    • exec Family: execlp
    • exec Family: execle
    • exec Family: execv
    • exec Family: execvp
    • exec Family: execve
    • exec error handling
  • Wait!
    • Problem 1: Without Wait?
    • Sleep
    • Problem 2: Zombies!
    • Wait System Call
    • waitpid
Powered by GitBook
On this page

Was this helpful?

  1. Let's Fork! Process Creation

Distinguish Parent and Child Process

Before we discuss in details, let's try the following code:

/* LetsFork/fork2.c */
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

int main(int argc,char* argv[])
{
    int res;
    printf("Before fork():PID[%d]\n",getpid());
    res = fork();
    printf("The value of res is %d\n",res);
    if(res == 0)
    {   
        printf("I am child! PID: [%d]\n",getpid());
    }
    else
    {
        printf("I am parent! PID: [%d]\n",getpid());
    }
    printf("Program Terminated!\n");
    return 0;
}

The output is as follows:

The original process has the PID 2072. After res = fork();, the process splits into two, the parent and child.

For the parent, the return value of fork() is the PID of the new child. However, for the child, the return value is 0.

By using this condition, we can distinguish parent and child.

Previousfork system callNextExercises

Last updated 5 years ago

Was this helpful?