0% found this document useful (0 votes)
5 views14 pages

Lab-05

This document outlines the use of system calls in UNIX-like operating systems for creating and managing child processes. It covers the fork(), exec(), wait(), and sleep() system calls, detailing their functionalities, syntax, and error handling. Additionally, it provides graded tasks for practical implementation of these concepts in programming exercises.

Uploaded by

ahmedmukarram6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views14 pages

Lab-05

This document outlines the use of system calls in UNIX-like operating systems for creating and managing child processes. It covers the fork(), exec(), wait(), and sleep() system calls, detailing their functionalities, syntax, and error handling. Additionally, it provides graded tasks for practical implementation of these concepts in programming exercises.

Uploaded by

ahmedmukarram6
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

1

Using Fork, Exec, Wait & Exit System Calls for Creating
Child Processes

Objective:
This lab describes how a program can execute, wait, terminate, and
control children processes using system calls.
Activity Outcomes:
On completion of this lab students will be able to:
• Write programs that uses process creation system call fork ()
• Use exec system call
• Use wait system call
• Use sleep system call

1. fork() System Call:


• fork() creates a new process by duplicating the calling process. The new process is the
child, and the original process is the parent.
2

2. exec() System Call:


• exec() replaces the current process image with a new process image. It is used to run
another program from within a program.
3

wait ( ) | Process Completion


3. wait() System Call:
• wait() makes the parent process wait for its child process to finish.

• Child process may terminate due to any of these:


• It calls exit( );
•  It returns (an int) from main
•  It receives a signal (from the OS or another process) whose default action is to terminate.
• Wait ( ) will force a parent process to wait for a child process to stop or terminate. Wait ( )
return the pid of the child or -1 for an error.
• exit ( ):Exit () terminates the process which calls this function and returns the exit status
value. Both
• UNIX and C (forked) programs can read the exit status value.By convention, a status of 0
means normal
• termination. Any other value indicates an error or unusual occurrence.
4

Output:

4. sleep() System Call:


• sleep() pauses the execution of a process for a specified number of seconds.

• A process may suspend for a period of time using the sleep () command:
• Orphan Process: When a parent dies before its child, the child is automatically adopted by
the original “init” process whose PID is 1.
• Zombie Process: A process that terminates cannot leave the system until its parent accepts
its return code. If its parent process is already dead, it’ll already have been adopted by the
“init” process, which always accepts its children’s return codes (orphan). However, if a
process’s parent is alive but never executes a wait ( ), the process’s return code will never be
accepted and the process will remain a zombie.
5

Exec () System call – a family of six functions


The `exec()` system call is part of a family of functions in UNIXlike
operating systems (such as Linux) that are used to replace the current
process image with a new process image. Essentially, when a process
calls an `exec()` function, the current process is replaced with a new
program, and the process ID (PID) remains the same. The new program
starts executing from its entry point, and everything in the old program's
memory is lost.

The `exec()` family consists of six different functions, each designed to


execute a new program, with slight differences in how they handle
arguments and environment variables.
6

1. execl()
Syntax:
int execl(const char *path, const char *arg, ..., NULL);
• The `execl()` function takes a variable number of arguments.
• Each argument is passed to the new program as separate
parameters.
• Path: Path to the executable.
• arg: The first argument should be the name of the program
(conventionally).
• Other arguments follow and must end with a `NULL` pointer.

2. execv()
Syntax:
int execv(const char *path, char *const argv[]);
• This function is similar to `execl()`, but the arguments are passed
as an array rather than a variable number of arguments.
7

• argv: An array of strings representing the commandline arguments.

3.execle()
Syntax:
int execle(const char *path, const char *arg, ..., NULL, char *const
envp[]);
• `execle()` works like `execl()`, but also allows you to specify a
custom environment for the new process.
• envp: An array of strings representing the environment variables
for the new process.
8

4. execve()
Syntax:
int execve(const char *path, char *const argv[], char *const envp[]);
• `execve()` is the most fundamental `exec()` function and is the
system call that all other `exec()` functions internally use.
• It takes the path to the executable, the array of arguments, and an
array of environment variables.

5. execlp()
Syntax:
int execlp(const char *file, const char *arg, ..., NULL);
• The `execlp()` function behaves like `execl()`, but instead of
specifying the full path to the executable, the system searches for
the executable in the directories listed in the `PATH` environment
variable.
9

6. execvp()
Syntax:
int execvp(const char *file, char *const argv[]);
• Similar to `execv()`, `execvp()` takes the arguments as an array and
looks for the executable in the `PATH` environment variable.
• The `exec()` system call does not create a new process; it simply
replaces the current process image with a new program.
• After an `exec()` call, the original program ceases to exist, and the
new program runs in the same process.
• The PID of the process remains unchanged.
• If the `exec()` call is successful, it does not return. If it fails (e.g.,
if the executable is not found), the function returns `1` and sets
`errno` to indicate the error.
10

Example (using `execlp()`):

If successful, the `execlp()` call in this example will replace the current
process with the `ls` command, listing the directory contents. The process
does not return to the original program.
Summary of Differences:
|Function|Arguments (Command)|Arguments (Env Variables)|Path Search|
11

| `execl` | Variable list | No | No


|
| `execv` | Array | No | No
|
| `execle` | Variable list | Yes | No
|
| `execve` | Array | Yes | No
|
| `execlp` | Variable list | No | Yes
|
| `execvp` | Array | No | Yes

This family of functions provides flexibility depending on how you want


to pass arguments and environment variables to the new process.
Some bulletpoint guide on how to check and handle errors, ensure clean
process termination, and interpret status codes for the `fork()`, `exec()`,
`wait()`, and `exit()` system calls, without including code:

Error Handling
1. Fork System Call (`fork()`):
Check Return Value:
• If `fork()` returns a negative value, it indicates an error in creating
a new process.
Handle Success and Failure:
• If `fork()` returns `0`, you are in the child process.
• If `fork()` returns a positive value, you are in the parent
process, and the return value is the child’s process ID.
12

2. Exec System Call (`exec()`):


Check Return Value:
• `exec()` functions replace the current process image; they do not
return on success.
• if `exec()` fails, it returns `1`, and an error message can be
retrieved.
3. Wait System Call (`wait()` or `waitpid()`):
Check Return Value:
• If `wait()` or `waitpid()` returns `1`, it indicates an error in waiting
for the child process.
Handle Waiting Errors:
• Verify that the process ID passed to `wait()` matches the child
process.
4. Exit System Call (`exit()`):
• No Direct Return Value:
• `exit()` terminates the process and does not return a value. Ensure
that `exit()` is called in all scenarios where the process needs to
terminate.

Process Termination
1. Ensure Proper Exit in Child Process:
• Use `exit()`:
• The child process should call `exit()` to terminate properly.
2. Ensure Proper Exit in Parent Process:
• Wait for Child:
• The parent process should wait for the child to complete using
`wait()` or `waitpid()` to avoid premature termination and zombie
processes.
13

3. Handle Zombie Processes:


• Ensure Reaping:
• Always use `wait()` or `waitpid()` to handle the child process's exit
to prevent zombie processes.

Status Codes
1. Check Exit Status:
• Use `WIFEXITED(status)`:
• Check if the child process terminated normally.
2. Retrieve Exit Status:
• Use `WEXITSTATUS(status)`:
• Extract the exit status of the child process if it terminated
normally.
3. Check for Abnormal Termination:
• Use `WIFSIGNALED(status)`:
• Determine if the child process was terminated by a signal.
4. Check for Core Dumps:
• Use `WCOREDUMP(status)`:
• Check if the child process generated a core dump.
I’ve added the references links for more details:
https://www2.it.uu.se/education/course/homepage/os/vt18/module2/exec/
14

Graded Task:
In this activity, you are required to perform tasks given below:
1) Print something and Check id of the parent process [Estimated 5-10
mins]
2) Create a child process and print child process id in parent process.
[ Estimated 10 mins]
3) Create a process and make it an orphan. [Estimated 5 mins]
Hint: To, illustrate this insert a sleep statement into the child’s
code. This ensured that the parent process terminated before its
child.
4) Write a C/C++ program in which a parent process creates a child
process using a fork() system call. The child process takes your age
as input and parent process prints the age. [Estimated 10 mins]
5) Write a C++ program that creates an array of size 1000 and
populates it with random integers between 1 and 100. Now, it
creates two child processes. The first child process finds how many
prime numbers are there among first 500 number while the second
child process finds the number of prime numbers among the
remaining 500 numbers. [Estimated 20 mins]
6) Write a program that sets a custom environment variable (e.g.,
MY_VAR="HelloWorld") and then uses execle to execute
/usr/bin/env (a command that prints all environment variables).
[Estimated 5 mins]
7) Write a program that prompts the user to input a command, and
then uses execvp to execute the input command dynamically.
Example: If the user inputs ps, the program will run execvp("ps", args);.

[Estimated 10 mins]

You might also like