Lab03 Processes
Lab03 Processes
Lab 03
1
Lab Objective
• To practice creating child process using
fork().
2
The fork Function
• In computing, when a process forks, it
creates a copy of itself, which is called a
"child process." The original process is
then called the "parent process .
• The fork() function is used from a
parent process to create a duplicate
process, the child .
• The parent and the child processes can tell
each other apart by examining the return
value of the fork() system call
3
The fork Function
pid_t fork(void);
5
Practice
Ex1:
• In the following C++ program, the main
process forks two children.
• Every child repeats adding the value 1 to
the variable “a” ten times.
• Write, compile and run the program in
Linux.
8
1st fork()
>0 0
Parent Child 1
Add 1 to a
ten times,
2nd fork() one each
second
0
Parent Child 2
Wait for child Add 1 to a
termination ten times,
one each
second
9
#include <iostream>
#include <stdlib.h> /* exit() */
#include <unistd.h> /* fork() */
#include <sys/types.h> /* pid_t */
#include <sys/wait.h> /* wait() */
using std::cout; // it is a predefined variable which
allow to send data to the console to be printed as
The main process
text. It stands for “character output” forks child 1
17
Output
18
Notes
• wait() System Call
This function blocks the calling process until one of its child processes exits or
a signal is received. wait() takes the address of an integer variable and returns
the process ID of the completed process.
• The main() should be declared as int , because when you declare it as void,
it causes an error.
10
Output
16
fork() in C
Samar Alsaleh 19
OS - CS242 - Spring 2009
Process Termination
• Process executes last statement and asks
the operating system to delete it (exit)
• Parent may terminate execution of
children processes (abort)
– Child has exceeded allocated resources
– Task assigned to child is no longer required
– If parent is exiting
• Some operating systems do not allow child to
continue if its parent terminates.
27
Check Off on Ex1
28
Important
• The ps Command
Source:
https://docs.oracle.com/cd/E19455-01/805-7229/6j6q8svgp/
index.html 32
Important
• The ps Command
Source:
https://docs.oracle.com/cd/E19455-01/805-7229/6j6q8svgp/
index.html 33
??? ANY QUESTIONS ???
J
34