SlideShare ist ein Scribd-Unternehmen logo
1 von 46
BITS, PILANI – K. K. BIRLA GOA CAMPUS
Operating Systems
(IS ZC362)
by
Mrs. Shubhangi Gawali
Dept. of CS and IS
07/16/14
BITS, PILANI – K.
K. BIRLA GOA
CAMPUS 1
2
 Parent process create children
processes, which, in turn create other
processes, forming a tree of processes
 Generally, process identified and managed via a
process identifier (pid)
 Resource sharing
Parent and children share all resources
Children share subset of parent’s resources
Parent and child share no resources
 Execution
Parent and children execute concurrently
Parent waits until children terminate
3
 Address space
◦ Child duplicate of parent
◦ Child has a program loaded into it
 UNIX examples
◦ fork system call creates new process
◦ exec system call used after a fork to replace the process’
memory space with a new program
4
5
 If fork() returns a negative value, the creation of a
child process was unsuccessful.
 fork() returns a zero to the newly created child
process.
 fork() returns a positive value, the process ID of
the child process, to the parent.
6
7
8
#include <stdio.h> #include
<sys/types.h> void
ChildProcess(void); void
ParentProcess(void); void
main(void)
{
pid_t pid;
pid = fork();
if (pid == 0)
ChildProcess();
else
ParentProcess();
}
void ChildProcess(void) {
int i;
for (i =1; i<= 10; i++)
printf(“child, i=%dn", i);
printf(“child done n");
}
void ParentProcess(void) {
int i;
for (i=1; i<= 10; i++)
printf(“parent, i= %dn", i);
printf(“parent donen"); }
9
10
11
12
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
int main(){
pid_t pid;
printf(“fork program starting n”);
pid = fork();
if (pid < 0 ){ perror(“fork failedn”); exit(1); }
else if (pid == 0){
printf(“ This is from child process My PID is %d and my Parent PID is
%dn”,getpid(),getppid()); }
else { printf(“This is from parent process My PID is %d and my Child’s PID
is %dn”,getpid(),pid); wait(NULL); } // common to parent and child
return 0;
}
13
 Each process is allowed to have a unique number named process
identifier or PID
◦ usually between 2 and 32767 (/proc/sys/kernel/pid_max)
◦ 64 bit  maximum PID number up to 4194303
 Next unused number is chosen as process ID
 Once upper limit of 32767 is reached then the numbers restart at 2 so
that they wrap around.
 PID 1 is init process, Process 0 is swapper or sched (Process 0 is
responsible for paging)
 Process has its own code, data, stack, environment space, program
counter etc.
 Process table contains information about all the processes that are
currently loaded with
14
fork
 pid_t fork(void)
◦ Duplicates the current process, creating a new entry in the
process table with many of the same attributes as the parent
process.
◦ The new process is almost identical to the original, executing
the same code but with its own data space, environment and
file descriptor.
◦ Uses copy on write technique
◦ Kernel internally invokes do_fork() function (in fork.c)
15
The fork ( ) system call does the following in a UNIX
system
◦ Allocates slot in the process table for the new process
◦ Assigns a unique process id to the new process
◦ Make a copy of the process image of the parent, with the
exception of shared memory
◦ Increases counters for any files owned by the parent, to reflect
that an additional process now also owns these files.
◦ Assigns the child process a ready state
◦ Returns the Process ID number (PID) of the child to the parent
process and a 0 value to the child process.
16
All this work is done in Kernel space of parent process
After completing these functions, OS will do the following
operations as a part of dispatcher routine
 Control returns to the user mode at the point of the fork
call of the parent
 Transfer control to the child process. The child process
begins executing at the same point in the code as the
parent, namely at the return from the fork call
 Transfer control to another process. Both child and parent
are left in the ready state
 If fork system call fails, the return value to parent (no child
will be created) will be -1 17
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
int main()
{
if(fork())
if(fork())
fork();
return 0;
}
P1
P2 P3 p4
18
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
int main()
{
printf(“fork program starting n”);
if( fork( ))
if(!fork( ) )
fork( );
return 0;
}
19
P1
P2 P3
p4
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
int main()
{
if(!fork())
if(!fork())
fork();
return 0;
}
P1
P2
P3
p4
20
21
int x=0;
int main()
{
for(i=0;i<2;i++)
{
fork();
x=x+5;
}
return 0;
}
P1
P2 P3
p4
X = 10
X = 10
X = 10
X = 10
Number of new processes created is 3
Final value of x in P1 is 10
Final value of x in P2 is 10
Final value of x in P3 is 10
Final value of x in P4 is 10
The Unix process management model is split
into two distinct operations :
1. The creation of a process.
2. The running of a new program.
 The creation of a new process is done using
the fork() system call.
 A new program is run using the
exec(l,lp,le,v,vp) family of system calls.
 These are two separate functions which may
be used independently.
1.A call to fork() will create a completely
separate sub-process which will be exactly
the same as the parent.
2.The process that initiates the call to fork is
called the parent process.
3.The new process created by fork is called the
child process.
4.The child gets a copy of the parent's text and
memory space.
5.They do not share the same memory .
fork() system call returns an integer to both the
parent and child processes:
 -1 this indicates an error with no child
process created.
 A value of zero indicates that the child
process code is being executed.
 Positive integers represent the child’s process
identifier (PID) and the code being executed is
in the parent’s process.
if ( (pid = fork()) == 0)
printf(“I am the childn”);
else
printf(“I am the parentn”);
 Process 0 is created by the system boot code.
 All other processes are created by the fork system call.
 After a fork, both parent and child processes resume
execution at the return of the fork function.
 The child process contains copies of the parent's text,
data, and stack segments. The child process has file
descriptors that contains references to the same opened
files as its parent, so they both share the same file
pointer to each opened file.
27
When the child process calls exec(), all data in the
original program is lost, and it is replaced with a
running copy of the new program.
Calling one of the exec() family will terminate the
currently running program and starts executing a new
one which is specified in the parameters of exec in the
context of the existing process.
The process id is not changed.
 If the exec command fails, then it returns 1.
Using exec, an executable binary file (eg: a.out)
can be converted into a process.
 An example of using exec is implementing a
shell program or a command interpreter.
 A shell program takes user commands and
executes them.
 int execl( const char *path, const char *arg, ...);
 int execlp( const char *file, const char *arg, ...);
 int execle( const char *path, const char *arg , ...,
char * const envp[]);
 int execv( const char *path, char *const argv[]);
 int execvp( const char *file, char *const argv[]);
The first difference in these functions is that the first
four take a pathname argument while the last two
take a filename argument. When a filename argument
is specified:
• if filename contains a slash, it is taken as a
pathname.
• otherwise the executable file is searched for in the
directories specified by the PATH environment
variable.
 execl- takes the path name of a binary
executable as its first argument, the rest of the
arguments are the command line arguments
ending with a NULL.
 Example: execl("./a.out", NULL)
32
 execv – takes the path name of a binary
executable as its first argument, and an array of
arguments as its second argument.
 Example: static char* args[] = {“ “,
"cat.txt", "test1.txt", NULL};
 execv("/bin/cp", args);
 The empty string “ “ can be replaced by the
command itself (eg “ls”) or leave it as “ “.
33
 execlp - same as execl except that we don’t
have to give the full path name of the command.
 Example: execlp("ls", NULL)
34
35
36
When a program wants to have another
program running in parallel, it will typically
first use fork, then the child process will use
exec to actually run the desired program.
 wait, waitpid - wait for a child process to stop or terminate
#include <sys/wait.h>
pid_t wait(int *status);
pid_t waitpid(pid_t pid, int *status, int options);
 It pause / suspends the parent process until one of its child
processes is exited or until a signal is delivered whose action is to
terminate the parent or child process or to call a signal handling
function.
 It returns the PID of the child and the exit status gets placed in
status.
 To prevent the child becoming a zombie the parent should call wait
 on its children, either periodically or upon receiving the SIGCHLD
 signal, which indicates a child process has terminated.
38
 If a child has already exited by the time of the call, the
function returns immediately and system resources
used by the child are freed.
 The call returns the PID of the child process (when
child process terminates) on success.
 The status information allows the parent process to
determine the exit status of the child process. i.e the
value returned from main or passed by exit.
 If status is not a null pointer, the status information will
be written to the location to which it points.
39
In waitpid() the value of pid can be
 < -1 which means to wait for any child process whose
process group ID is equal to the absolute value of pid.
 -1 which means to wait for any child process;
this is the same behavior which wait exhibits.
 0 which means to wait for any child process
whose process group ID is equal to that of the calling
process.
 > 0 which means to wait for the child whose
process ID is equal to the value of pid.
40
int main() {
int child_status, pid, pidwait;
if ((pid = fork()) == 0) {
printf(“This is the child!n”);
}
else {
pidwait = wait(&child_status);
printf(“child %d has terminatedn”, pidwait);
}
return 0;
}
41
42
else if (pid == 0) {
printf(“ This is from child
process I am exitingn”);
exit(2);
}
else {
printf(“This is from parent
processn”);
}
wait(&status);
// waitpid(pid, &status,0);
// Child is no more and this part is
only for Parent
printf(“Child exited already now
with exit status %dn”,status);
return 0;
}
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
int main()
{
pid_t pid;
int status;
printf(“fork program starting n”);
pid = fork();
if (pid < 0 ){
perror(“fork failedn”);
exit(1);
}
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main()
{ printf("fork program starting with pid %dn",getpid());
fork();
fork();
printf("My PID=%d My PPID = %dn",getpid(),getppid());
wait(NULL);
wait(NULL);
return 0;
}
July 16, 2014 43
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main()
{ int i;
printf("fork program starting with pid %dn",getpid());
for(i=0;i<2;i++)
fork();
printf("My PID=%d My PPID = %dn",getpid(),getppid());
while(wait(NULL)!= -1);
return 0;
}
July 16, 2014 44
 System function exit allows termination of a
process.
 Prototype :
#include <stdlib.h>
void exit(int status);
 The value of the status may be
EXIT_SUCCESS(0), EXIT_FAILURE(1) or any
other value that is available to a parent process.
45
Process related Commands
 The process related system calls in UNIX include
fork( ), exec( ) [many variations of this],
wait( ) and exit( ) system calls.
 Using exec, an executable binary file (eg:
a.out) can be converted into a process.
46

Weitere ähnliche Inhalte

Was ist angesagt?

Compiler Design
Compiler DesignCompiler Design
Compiler Design
Mir Majid
 

Was ist angesagt? (20)

Process creation and termination In Operating System
Process creation and termination In Operating SystemProcess creation and termination In Operating System
Process creation and termination In Operating System
 
File Management in Operating System
File Management in Operating SystemFile Management in Operating System
File Management in Operating System
 
CPU Scheduling in OS Presentation
CPU Scheduling in OS  PresentationCPU Scheduling in OS  Presentation
CPU Scheduling in OS Presentation
 
Multithreading
MultithreadingMultithreading
Multithreading
 
Os Threads
Os ThreadsOs Threads
Os Threads
 
Introduction to System Calls
Introduction to System CallsIntroduction to System Calls
Introduction to System Calls
 
Deadlock
DeadlockDeadlock
Deadlock
 
Disk scheduling
Disk schedulingDisk scheduling
Disk scheduling
 
Demand paging
Demand pagingDemand paging
Demand paging
 
Micro program example
Micro program exampleMicro program example
Micro program example
 
operating system lecture notes
operating system lecture notesoperating system lecture notes
operating system lecture notes
 
Semaphore
SemaphoreSemaphore
Semaphore
 
Asynchronous data transfer
Asynchronous data transferAsynchronous data transfer
Asynchronous data transfer
 
System calls
System callsSystem calls
System calls
 
Cpu scheduling in operating System.
Cpu scheduling in operating System.Cpu scheduling in operating System.
Cpu scheduling in operating System.
 
Computer architecture input output organization
Computer architecture input output organizationComputer architecture input output organization
Computer architecture input output organization
 
Dynamic interconnection networks
Dynamic interconnection networksDynamic interconnection networks
Dynamic interconnection networks
 
Compiler Design
Compiler DesignCompiler Design
Compiler Design
 
Virtual memory ppt
Virtual memory pptVirtual memory ppt
Virtual memory ppt
 
Processes and threads
Processes and threadsProcesses and threads
Processes and threads
 

Ähnlich wie process creation OS

Mychurch File Upload
Mychurch File UploadMychurch File Upload
Mychurch File Upload
Joe Suh
 
System Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbs
System Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbsSystem Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbs
System Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbs
ashukiller7
 
02 fundamentals
02 fundamentals02 fundamentals
02 fundamentals
sirmanohar
 

Ähnlich wie process creation OS (20)

What is-a-computer-process-os
What is-a-computer-process-osWhat is-a-computer-process-os
What is-a-computer-process-os
 
Os lab final
Os lab finalOs lab final
Os lab final
 
OS presentation (1).pptx
OS presentation (1).pptxOS presentation (1).pptx
OS presentation (1).pptx
 
computer notes - Inter process communication
computer notes - Inter process communicationcomputer notes - Inter process communication
computer notes - Inter process communication
 
Mychurch File Upload
Mychurch File UploadMychurch File Upload
Mychurch File Upload
 
UNIX_Process Control_Module3.pptx
UNIX_Process Control_Module3.pptxUNIX_Process Control_Module3.pptx
UNIX_Process Control_Module3.pptx
 
Lect3 process
Lect3 processLect3 process
Lect3 process
 
11_UNIX_Processes_Including_Select.ppt
11_UNIX_Processes_Including_Select.ppt11_UNIX_Processes_Including_Select.ppt
11_UNIX_Processes_Including_Select.ppt
 
Process management
Process managementProcess management
Process management
 
Lecture_Slide_4.pptx
Lecture_Slide_4.pptxLecture_Slide_4.pptx
Lecture_Slide_4.pptx
 
Systems Programming Assignment Help - Processes
Systems Programming Assignment Help - ProcessesSystems Programming Assignment Help - Processes
Systems Programming Assignment Help - Processes
 
Process threads operating system.
Process threads operating system.Process threads operating system.
Process threads operating system.
 
اسلاید اول جلسه هشتم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه هشتم کلاس پایتون برای هکرهای قانونیاسلاید اول جلسه هشتم کلاس پایتون برای هکرهای قانونی
اسلاید اول جلسه هشتم کلاس پایتون برای هکرهای قانونی
 
Linux Programming
Linux ProgrammingLinux Programming
Linux Programming
 
Lecture2 process structure and programming
Lecture2   process structure and programmingLecture2   process structure and programming
Lecture2 process structure and programming
 
System Calls - Introduction
System Calls - IntroductionSystem Calls - Introduction
System Calls - Introduction
 
04_ForkPipe.pptx
04_ForkPipe.pptx04_ForkPipe.pptx
04_ForkPipe.pptx
 
System Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbs
System Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbsSystem Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbs
System Calls.pptxnsjsnssbhsbbebdbdbshshsbshsbbs
 
Linux basics
Linux basicsLinux basics
Linux basics
 
02 fundamentals
02 fundamentals02 fundamentals
02 fundamentals
 

Kürzlich hochgeladen

CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
anilsa9823
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
anilsa9823
 

Kürzlich hochgeladen (20)

Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 

process creation OS

  • 1. BITS, PILANI – K. K. BIRLA GOA CAMPUS Operating Systems (IS ZC362) by Mrs. Shubhangi Gawali Dept. of CS and IS 07/16/14 BITS, PILANI – K. K. BIRLA GOA CAMPUS 1
  • 2. 2
  • 3.  Parent process create children processes, which, in turn create other processes, forming a tree of processes  Generally, process identified and managed via a process identifier (pid)  Resource sharing Parent and children share all resources Children share subset of parent’s resources Parent and child share no resources  Execution Parent and children execute concurrently Parent waits until children terminate 3
  • 4.  Address space ◦ Child duplicate of parent ◦ Child has a program loaded into it  UNIX examples ◦ fork system call creates new process ◦ exec system call used after a fork to replace the process’ memory space with a new program 4
  • 5. 5
  • 6.  If fork() returns a negative value, the creation of a child process was unsuccessful.  fork() returns a zero to the newly created child process.  fork() returns a positive value, the process ID of the child process, to the parent. 6
  • 7. 7
  • 8. 8
  • 9. #include <stdio.h> #include <sys/types.h> void ChildProcess(void); void ParentProcess(void); void main(void) { pid_t pid; pid = fork(); if (pid == 0) ChildProcess(); else ParentProcess(); } void ChildProcess(void) { int i; for (i =1; i<= 10; i++) printf(“child, i=%dn", i); printf(“child done n"); } void ParentProcess(void) { int i; for (i=1; i<= 10; i++) printf(“parent, i= %dn", i); printf(“parent donen"); } 9
  • 10. 10
  • 11. 11
  • 12. 12
  • 13. #include <stdio.h> #include <unistd.h> #include <errno.h> #include <sys/types.h> int main(){ pid_t pid; printf(“fork program starting n”); pid = fork(); if (pid < 0 ){ perror(“fork failedn”); exit(1); } else if (pid == 0){ printf(“ This is from child process My PID is %d and my Parent PID is %dn”,getpid(),getppid()); } else { printf(“This is from parent process My PID is %d and my Child’s PID is %dn”,getpid(),pid); wait(NULL); } // common to parent and child return 0; } 13
  • 14.  Each process is allowed to have a unique number named process identifier or PID ◦ usually between 2 and 32767 (/proc/sys/kernel/pid_max) ◦ 64 bit  maximum PID number up to 4194303  Next unused number is chosen as process ID  Once upper limit of 32767 is reached then the numbers restart at 2 so that they wrap around.  PID 1 is init process, Process 0 is swapper or sched (Process 0 is responsible for paging)  Process has its own code, data, stack, environment space, program counter etc.  Process table contains information about all the processes that are currently loaded with 14
  • 15. fork  pid_t fork(void) ◦ Duplicates the current process, creating a new entry in the process table with many of the same attributes as the parent process. ◦ The new process is almost identical to the original, executing the same code but with its own data space, environment and file descriptor. ◦ Uses copy on write technique ◦ Kernel internally invokes do_fork() function (in fork.c) 15
  • 16. The fork ( ) system call does the following in a UNIX system ◦ Allocates slot in the process table for the new process ◦ Assigns a unique process id to the new process ◦ Make a copy of the process image of the parent, with the exception of shared memory ◦ Increases counters for any files owned by the parent, to reflect that an additional process now also owns these files. ◦ Assigns the child process a ready state ◦ Returns the Process ID number (PID) of the child to the parent process and a 0 value to the child process. 16
  • 17. All this work is done in Kernel space of parent process After completing these functions, OS will do the following operations as a part of dispatcher routine  Control returns to the user mode at the point of the fork call of the parent  Transfer control to the child process. The child process begins executing at the same point in the code as the parent, namely at the return from the fork call  Transfer control to another process. Both child and parent are left in the ready state  If fork system call fails, the return value to parent (no child will be created) will be -1 17
  • 18. #include <stdio.h> #include <unistd.h> #include <errno.h> #include <sys/types.h> int main() { if(fork()) if(fork()) fork(); return 0; } P1 P2 P3 p4 18
  • 19. #include <stdio.h> #include <unistd.h> #include <errno.h> #include <sys/types.h> int main() { printf(“fork program starting n”); if( fork( )) if(!fork( ) ) fork( ); return 0; } 19 P1 P2 P3 p4
  • 20. #include <stdio.h> #include <unistd.h> #include <errno.h> #include <sys/types.h> int main() { if(!fork()) if(!fork()) fork(); return 0; } P1 P2 P3 p4 20
  • 21. 21 int x=0; int main() { for(i=0;i<2;i++) { fork(); x=x+5; } return 0; } P1 P2 P3 p4 X = 10 X = 10 X = 10 X = 10 Number of new processes created is 3 Final value of x in P1 is 10 Final value of x in P2 is 10 Final value of x in P3 is 10 Final value of x in P4 is 10
  • 22. The Unix process management model is split into two distinct operations : 1. The creation of a process. 2. The running of a new program.
  • 23.  The creation of a new process is done using the fork() system call.  A new program is run using the exec(l,lp,le,v,vp) family of system calls.  These are two separate functions which may be used independently.
  • 24. 1.A call to fork() will create a completely separate sub-process which will be exactly the same as the parent. 2.The process that initiates the call to fork is called the parent process. 3.The new process created by fork is called the child process. 4.The child gets a copy of the parent's text and memory space. 5.They do not share the same memory .
  • 25. fork() system call returns an integer to both the parent and child processes:  -1 this indicates an error with no child process created.  A value of zero indicates that the child process code is being executed.  Positive integers represent the child’s process identifier (PID) and the code being executed is in the parent’s process.
  • 26. if ( (pid = fork()) == 0) printf(“I am the childn”); else printf(“I am the parentn”);
  • 27.  Process 0 is created by the system boot code.  All other processes are created by the fork system call.  After a fork, both parent and child processes resume execution at the return of the fork function.  The child process contains copies of the parent's text, data, and stack segments. The child process has file descriptors that contains references to the same opened files as its parent, so they both share the same file pointer to each opened file. 27
  • 28. When the child process calls exec(), all data in the original program is lost, and it is replaced with a running copy of the new program. Calling one of the exec() family will terminate the currently running program and starts executing a new one which is specified in the parameters of exec in the context of the existing process. The process id is not changed.  If the exec command fails, then it returns 1.
  • 29. Using exec, an executable binary file (eg: a.out) can be converted into a process.  An example of using exec is implementing a shell program or a command interpreter.  A shell program takes user commands and executes them.
  • 30.  int execl( const char *path, const char *arg, ...);  int execlp( const char *file, const char *arg, ...);  int execle( const char *path, const char *arg , ..., char * const envp[]);  int execv( const char *path, char *const argv[]);  int execvp( const char *file, char *const argv[]);
  • 31. The first difference in these functions is that the first four take a pathname argument while the last two take a filename argument. When a filename argument is specified: • if filename contains a slash, it is taken as a pathname. • otherwise the executable file is searched for in the directories specified by the PATH environment variable.
  • 32.  execl- takes the path name of a binary executable as its first argument, the rest of the arguments are the command line arguments ending with a NULL.  Example: execl("./a.out", NULL) 32
  • 33.  execv – takes the path name of a binary executable as its first argument, and an array of arguments as its second argument.  Example: static char* args[] = {“ “, "cat.txt", "test1.txt", NULL};  execv("/bin/cp", args);  The empty string “ “ can be replaced by the command itself (eg “ls”) or leave it as “ “. 33
  • 34.  execlp - same as execl except that we don’t have to give the full path name of the command.  Example: execlp("ls", NULL) 34
  • 35. 35
  • 36. 36
  • 37. When a program wants to have another program running in parallel, it will typically first use fork, then the child process will use exec to actually run the desired program.
  • 38.  wait, waitpid - wait for a child process to stop or terminate #include <sys/wait.h> pid_t wait(int *status); pid_t waitpid(pid_t pid, int *status, int options);  It pause / suspends the parent process until one of its child processes is exited or until a signal is delivered whose action is to terminate the parent or child process or to call a signal handling function.  It returns the PID of the child and the exit status gets placed in status.  To prevent the child becoming a zombie the parent should call wait  on its children, either periodically or upon receiving the SIGCHLD  signal, which indicates a child process has terminated. 38
  • 39.  If a child has already exited by the time of the call, the function returns immediately and system resources used by the child are freed.  The call returns the PID of the child process (when child process terminates) on success.  The status information allows the parent process to determine the exit status of the child process. i.e the value returned from main or passed by exit.  If status is not a null pointer, the status information will be written to the location to which it points. 39
  • 40. In waitpid() the value of pid can be  < -1 which means to wait for any child process whose process group ID is equal to the absolute value of pid.  -1 which means to wait for any child process; this is the same behavior which wait exhibits.  0 which means to wait for any child process whose process group ID is equal to that of the calling process.  > 0 which means to wait for the child whose process ID is equal to the value of pid. 40
  • 41. int main() { int child_status, pid, pidwait; if ((pid = fork()) == 0) { printf(“This is the child!n”); } else { pidwait = wait(&child_status); printf(“child %d has terminatedn”, pidwait); } return 0; } 41
  • 42. 42 else if (pid == 0) { printf(“ This is from child process I am exitingn”); exit(2); } else { printf(“This is from parent processn”); } wait(&status); // waitpid(pid, &status,0); // Child is no more and this part is only for Parent printf(“Child exited already now with exit status %dn”,status); return 0; } #include <stdio.h> #include <unistd.h> #include <errno.h> #include <sys/types.h> #include <sys/wait.h> int main() { pid_t pid; int status; printf(“fork program starting n”); pid = fork(); if (pid < 0 ){ perror(“fork failedn”); exit(1); }
  • 43. #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> int main() { printf("fork program starting with pid %dn",getpid()); fork(); fork(); printf("My PID=%d My PPID = %dn",getpid(),getppid()); wait(NULL); wait(NULL); return 0; } July 16, 2014 43
  • 44. #include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> int main() { int i; printf("fork program starting with pid %dn",getpid()); for(i=0;i<2;i++) fork(); printf("My PID=%d My PPID = %dn",getpid(),getppid()); while(wait(NULL)!= -1); return 0; } July 16, 2014 44
  • 45.  System function exit allows termination of a process.  Prototype : #include <stdlib.h> void exit(int status);  The value of the status may be EXIT_SUCCESS(0), EXIT_FAILURE(1) or any other value that is available to a parent process. 45
  • 46. Process related Commands  The process related system calls in UNIX include fork( ), exec( ) [many variations of this], wait( ) and exit( ) system calls.  Using exec, an executable binary file (eg: a.out) can be converted into a process. 46

Hinweis der Redaktion

  1. If the call to fork() is executed successfully, Unix will make two identical copies of address spaces, one for the parent and the other for the child. Both processes will start their execution at the next statement following the fork() call. In this case, both processes will start their execution at the assignment statement as shown.
  2. Both processes start their execution right after the system call fork(). Since both processes have identical but separate address spaces, those variables initialized before the fork() call have the same values in both address spaces. Since every process has its own address space, any modifications will be independent of the others. In other words, if the parent changes the value of its variable, the modification will only affect the variable in the parent process&amp;apos;s address space. Other address spaces created by fork() calls will not be affected even though they have identical variable names.
  3. In this program, both processes print lines that indicate (1) whether the line is printed by the child or by the parent process, and (2) the value of variable i. For simplicity, printf() is used.
  4. When the main program executes fork(), an identical copy of its address space, including the program and all data, is created. System call fork() returns the child process ID to the parent and returns 0 to the child process. The following figure shows that in both address spaces there is a variable pid. The one in the parent receives the child&amp;apos;s process ID 3456 and the one in the child receives 0.
  5. Now both programs (i.e., the parent and child) will execute independent of each other starting at the next statement:
  6. In the parent, since pid is non-zero, it calls function ParentProcess(). On the other hand, the child has a zero pid and calls ChildProcess() as shown. Due to the fact that these processes are run concurrently, their output lines are intermixed in a rather unpredictable way. Moreover, the order of these lines are determined by the CPU scheduler. Hence, if you run this program again, you may get a totally different result. Due to the fact that the CPU scheduler will assign a time quantum to each process, the parent or the child process will run for some time before the control is switched to the other and the running process will print some lines before you can see any line printed by the other process.