0% found this document useful (0 votes)
96 views

Os Lab - Da2

This document provides information about process creation and execution in Linux operating systems. It discusses key concepts such as how processes are created using the fork() system call, with the parent process creating a child process. The child process is a copy of the parent process but with its own process ID. Both parent and child processes continue executing after forking. The document also describes how to monitor running processes using commands like ps and shows how to get the process ID and parent process ID of the current process. Sample C programs are provided to demonstrate process creation and the use of wait() to wait for a child process to terminate before continuing.

Uploaded by

gonugunta phani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
96 views

Os Lab - Da2

This document provides information about process creation and execution in Linux operating systems. It discusses key concepts such as how processes are created using the fork() system call, with the parent process creating a child process. The child process is a copy of the parent process but with its own process ID. Both parent and child processes continue executing after forking. The document also describes how to monitor running processes using commands like ps and shows how to get the process ID and parent process ID of the current process. Sample C programs are provided to demonstrate process creation and the use of wait() to wait for a child process to terminate before continuing.

Uploaded by

gonugunta phani
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

OPERATING SYSTEMS

SWE3001

LAB DA-2

THILAKRAJ C - 20MIS0401
FACULTY: SRINIVAS KOPPU
SLOT: F1+TF1
SESSION – 2
Process Creation and Execution
Process Creation Concepts:
Processes are the primitive units for allocation of system resources. Each
process has its own address space and (usually) one thread of control. A
process executes a program; you can have multiple processes executing the
same program, but each process has its own copy of the program within its
own address space and executes it independently of the other copies.
Processes are organized hierarchically. Each process has a parent process,
which explicitly arranged to create it. The processes created by a given
parent are called its child processes. A child inherits many of its attributes
from the parent process.
A process ID number names each process. A unique process ID is allocated
to each process when it is created. The lifetime of a process ends when its
termination is reported to its parent process; at that time, all of the process
resources, including its process ID, are freed.
Processes are created with the fork() system call (so the operation of
creating a new process is sometimes called forking a process). The child
process created by fork is a copy of the original parent process, except that
it has its own process ID.
After forking a child process, both the parent and child processes continue
to execute normally. If you want your program to wait for a child process
to finish executing before continuing, you must do this explicitly after the
fork operation, by calling wait() or waitpid(). These functions give you
limited information about why the child terminated--for example, its exit
status code.
A newly forked child process continues to execute the same program as its
parent process, at the point where the fork call returns. You can use the
return value from fork to tell whether the program is running in the parent
process or the child process.
When a child process terminates, its death is communicated to its parent so
that the parent maytake some appropriate action. A process that is waiting
for its parent to accept its return code is called a zombie process. If a
parent dies before its child, the child (orphan process) is automatically
adopted by the original “init” process whose PID is 1.

Monitoring Processes:

1. List All Processes in Current Shell


If you run ps command without any arguments, it displays processes for
the current shell.
2. Print All Processes in Different Formats
Display every active process on a Linux system in generic (Unix/Linux)
format.
3. Display all processes in BSD format.
4. Display User Running Processes
You can select all processes owned by you using below command:
5.Print All Processes Running as Root
The command below enables you to view every process running with root
user privileges
6. Print Process Tree
A process tree shows how processes on the system are linked to each
other; processes whose parents have been killed are adopted by the init (or
systemd).
7. Process Threads
To print all threads of a process, use the -C flag, this will show the LWP
(light weight process)as well as NLWP (number of light weight process)
columns.
Process Identification:
The pid_t data type represents process IDs which is basically a signed
integer type (int). You can get the process ID of a process by calling
getpid(). The function getppid() returns the process ID of the parent of the
current process (this is also known as the parent process ID). Your program
should include the header files ‘unistd.h’ and ‘sys/types.h’ to use
thesefunctions.

Function: pid_t getpid (void)


The getpid() function returns the process ID of the current process.

Function: pid_t getppid (void)


The getppid() function returns the process ID of the parent of the current
process.

Creating Multiple Processes:


The fork function is the primitive for creating a process. It is declared in
the header file "unistd.h".

Function: pid_t fork (void)


The fork function creates a new process.
If the operation is successful, there are then both parent and child
processes and both see fork return, but with different values: it returns a
value of 0 in the child process and returns the child's process ID in the
parent process. If process creation
failed, fork returns a value of -1 inthe parent process and no child is
created.
ASSESSMENT QUESTIONS

Activities:
Work your way through the following exercises, demonstrating
your
knowledge of the material by answering the numbered
questions.

Submit a detailed lab report (Note: Your Lab report should be


Unique.)
Include the answers to the numbered questions.
Attach all source code that you have modified or written.
Attach sample output from the Programming Assignment.
Be prepared to demo the Programming Assignment next week
and to
answer questions about its operation.

Process Creation:
All processes in UNIX are created, or spawned, from existing
processes via the fork() system call. Both processes (parent and
child) continue execution after the call.

Review your classnotes, and read your textbook, the man pages, or
a reference book to understand what the fork() call does and how it
operates. Familiarize yourself with the ps (Process Status) utility
and its various options - it provides a great deal of useful
information about a process. Review the command-line mechanism
(&) for inducing background execution of a process and the sleep()
function for temporarily suspending execution of a process.

The two following sample programs illustrate the operation of the


fork() system
call.
Perform the following operations and answer the questions:

Sample Program 1
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h>
int main()
{
puts(“Before fork”);
fork();
puts(“After fork”);
return 0;
}
 Compile and run Sample Program 1

1. How many lines are printed by the program?


Ans- Three
2. Describe what is happening to produce the answer observed for the above question.
 insert a 10-second call to the function sleep() after the fork in Sample Program 1 and
recompile
 run Program 1 in the background (use &)

The three lines are printed immediately after execution. But when a sleep() of 10 seconds is
added, “After fork” is printed after 10secs.

Program
#include<stdio.h>
#include<sys/types.h>
#include<unistd.h> int main()
{
puts(“Before fork”);
fork();
sleep(10);
puts(“After fork”);
return 0;
}
3. Consult the man pages for the ps (process status) utility; they will help you
determine how to display and interpret the various types of information that is
reported. Then, using the appropriate options, observe and report the PIDs and the
status (i.e. state info) of your executing program. Provide a brief explanation of your
observations.
Perform the following operations and answer the questions:

Sample Program 2
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc,char* argv[]) {
int i, limit;
if(argc<2)
{
fputs(“Usage:must supply a limit value\n”,stderr);
exit(1);
}
limit = atoi(argv[1]);
fork();
fork();
printf(“PID#:%d\n”,getpid());
for(i=0;i<limit;i++)
printf(“%d\n”,i);
return 0;
}

Study the code for Sample Program 2 until you understand it.
4. Create a diagram illustrating how Sample Program 2 executes (i.e. give a process
hierarchydiagram, similar to the in-class exercise)
 Suggestion: run the program several times with a small input value (e.g. 10). Examine
the output carefully so that you understand exactly what is happening.

5. In the context of our classroom discussions on process state, process operations, and
especially process scheduling, describe what you observed and try explain what is
happeningto produce the observed results.

Ans - All processes in UNIX are created, or spawned, from existing processes via the fork()
system call. Both processes (parent and child) continue execution after the call. Here we
observe that the process passes through the various process states i.e New, Ready etc.
The scheduler (or process scheduler, as it is sometimes called) can be viewed as the code that
divides the finite resource of processor time between the runnable processes on a system.
Process Suspension and Termination:
This section introduces the wait() system call and the exit() function, which are usually
related as in parent and child. Note that there are several different versions of wait() (e.g.
some specify who to wait for). The exit() function causes program termination; resources are
recovered, files are closed, resource usage statistics are recorded, and the parent is notified
via a signal (provided it has executed a wait). Refer to the man pages to learn the syntax for
using these functions.

Sample Program 3
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main()
{
//use these variables
pid_t pid, child;
int status; if((pid=fork())<0)
{
perror("fork failure");
exit(1); }
else if(pid==0) {
printf("I am child PID %ld\n", (long) getpid()); exit(1);
}
else
{
pid=wait(&status);
printf("Child PID %ld terminated with return status %d\n",
(long)child,status);
}
return 0;
}
Perform the following operations and answer the questions:
 add function calls to Sample Program 3 so that it correctly uses wait() and exit().
Basically, implement the comments, making use of the pre-declared variables
referenced in the printf() statement.

6. Provide the exact line of code that you inserted for the wait() system call.
Ans - pid=wait(&status);

7. Who prints first, the child or the parent? Why?


Ans - Child prints first because parent waits for child to execute first. If wait() command is
not inserted then parent doesn’t wait and executes first with return value 0, after this child
prints the statement.
8. What two values are printed out by the parent in Sample Program 3? (No, not the
actualnumbers, but what they mean.) In other words, describe the interaction
between the exit() function and the wait() system call. You may want to experiment
by changing the value to better understand the interaction.
Ans - Child PID is printed by both child and parent. Parent also prints status. On changing
value passed to exit() the values of PIDs and status changes as follows:
Process Execution:
The exec() family of system calls provides a means of specifying that a process (typically the
just-spawned child) should be overlayed with a new executable. The child will then execute
different code from its parent. As mentioned in class, there are several different forms of the
exec() system call. Those with a 'v' (e.g. execve()) require a vector of pointers, whereas those
with an 'l' (e.g. execle()) expect a list of pointers. Those with an 'e' allow you to specify an
environmental variable, those with a 'p' allow you to specify a pathname to the executable.
The following sample program shows one form of the exec() call. It is used in this program to
execute any command (e.g. "ls", "ps") that is issued by the user.

Sample Program 4
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
int main(int argc,char* argv[]) {
if(argc<2)
{
fputs(“Usage:must supply a limit value\n”,stderr);
exit(1);
}
puts(“Before the exec”);
if(execvp(argv[1],&argv[1])<0){
perror(“exec failed”);
}
puts(“After the exec”);
return 0;
}
Perform the following operations and answer the questions:
 Compile, run and test Sample Program 4 using various commands (e.g. “date”, “ls”)
9. When is the second print line ("After the exec") printed? Explain your answer.
Ans - This line is printed after it’s done looking for the file specified. The line “After the
exec” is printed when the exit() system call is commented and when the execution fails due to
incorrect arguments of execvp() function.
10. Explain how the second argument passed to execvp() is used?
Ans - The second argument of execvp() system call is a pointer to the array of character
strings. The first argument gives the program file and the second argument gives the part that
needs to be displayed on the console.

THANKYOU

You might also like