21
Process Control Process Control

Process Control. Major Requirements of an Operating System Interleave the execution of several processes to maximize processor utilization while providing

Embed Size (px)

Citation preview

Page 1: Process Control. Major Requirements of an Operating System Interleave the execution of several processes to maximize processor utilization while providing

Process ControlProcess Control

Page 2: Process Control. Major Requirements of an Operating System Interleave the execution of several processes to maximize processor utilization while providing

Major Requirements of anMajor Requirements of anOperating SystemOperating System

Interleave the execution of several Interleave the execution of several processes to maximize processor processes to maximize processor utilization while providing reasonable utilization while providing reasonable response timeresponse time

Allocate resources to processesAllocate resources to processes

Support interprocess communication and Support interprocess communication and user creation of processesuser creation of processes

Page 3: Process Control. Major Requirements of an Operating System Interleave the execution of several processes to maximize processor utilization while providing

ProcessProcess

A program in executionA program in execution

Consists of three componentsConsists of three components– An executable programAn executable program– Associated data needed by the programAssociated data needed by the program– Execution context of the programExecution context of the program

All information the operating system needs to All information the operating system needs to manage the processmanage the process

Page 4: Process Control. Major Requirements of an Operating System Interleave the execution of several processes to maximize processor utilization while providing
Page 5: Process Control. Major Requirements of an Operating System Interleave the execution of several processes to maximize processor utilization while providing

UNIX Process StatesUNIX Process States

Page 6: Process Control. Major Requirements of an Operating System Interleave the execution of several processes to maximize processor utilization while providing
Page 7: Process Control. Major Requirements of an Operating System Interleave the execution of several processes to maximize processor utilization while providing

Process CreationProcess Creation

Submission of a batch jobSubmission of a batch job

User logs onUser logs on

Created to provide a service such as Created to provide a service such as printingprinting

Process creates another processProcess creates another process

Page 8: Process Control. Major Requirements of an Operating System Interleave the execution of several processes to maximize processor utilization while providing

Process CreationProcess Creation

A process may create other processesA process may create other processes– parent - childparent - child– process treeprocess tree

Each process needs resourcesEach process needs resources– CPU timeCPU time– memorymemory

Deciding how to allocate the resources is Deciding how to allocate the resources is a policy that is determined by the OSa policy that is determined by the OS

Page 9: Process Control. Major Requirements of an Operating System Interleave the execution of several processes to maximize processor utilization while providing

Process Creation DecisionsProcess Creation Decisions

Resource AllocationResource Allocation– Treat as a new processTreat as a new process– Divide parent’s resources among childrenDivide parent’s resources among children

ExecutionExecution– child runs concurrently with parentchild runs concurrently with parent– parent waits until some or all children terminateparent waits until some or all children terminate

Address SpaceAddress Space– copy of parentcopy of parent– new program loaded into address spacenew program loaded into address space

Page 10: Process Control. Major Requirements of an Operating System Interleave the execution of several processes to maximize processor utilization while providing

Unix process creationUnix process creation

A new process is created by the fork callA new process is created by the fork call

Child and parent are identical Child and parent are identical – child returns a 0child returns a 0– parent returns nonzeroparent returns nonzero

Both parent and child execute next lineBoth parent and child execute next line

Often the child executes an execOften the child executes an exec– creates a brand new process in its spacecreates a brand new process in its space

Parent can execute a waitParent can execute a wait

Page 11: Process Control. Major Requirements of an Operating System Interleave the execution of several processes to maximize processor utilization while providing

Example: Process Creation in Example: Process Creation in UnixUnix

int pid;int status = 0;

pid = fork()if (pid != 0) {

/* parent */…..pid = wait(&status);

} else {

/* child */…..exit(status);

}

int pid;int status = 0;

pid = fork()if (pid != 0) {

/* parent */…..pid = wait(&status);

} else {

/* child */…..exit(status);

}

Parent uses wait to sleep until the child exits; wait returns child pid and status.

Wait variants allow wait on a specific child, or notification of stops and other signals.

Wait has the effect of cleaning up the process out of the system – removes it from the zombie state.

Parent uses wait to sleep until the child exits; wait returns child pid and status.

Wait variants allow wait on a specific child, or notification of stops and other signals.

Wait has the effect of cleaning up the process out of the system – removes it from the zombie state.

The fork syscall returns twice: it returns a zero to the child and the child process ID (pid) to the parent.

The fork syscall returns twice: it returns a zero to the child and the child process ID (pid) to the parent.

Page 12: Process Control. Major Requirements of an Operating System Interleave the execution of several processes to maximize processor utilization while providing

Unix Unix Fork/Exec/Exit/WaitFork/Exec/Exit/Wait ExampleExample

fork parent fork child

wait exit

int pid = fork();Create a new process that is a clone of its parent.

exec*(“program” [, argvp, envp]);Overlay the calling process virtual memory with a new program, and transfer control to it.

exit(status);Exit with status, destroying the process.

int pid = wait*(&status);Wait for exit (or other status change) of a child.

exec

initialize child context

Page 13: Process Control. Major Requirements of an Operating System Interleave the execution of several processes to maximize processor utilization while providing

child1 = fork();if (child1 == 0){

/* I am the child process */child1P(one2two, two2one);

}else{

child2 = fork();if (child2 == 0){

/* I am the child process */child2P(one2two, two2one);

}else{

/* I am the parent *//* Wait for child one */waitpid(child1, status1, options); /* Wait for child two */ waitpid(child2, status2, options); printf("The children are finally finished\n");fflush(stdout);

}}

Page 14: Process Control. Major Requirements of an Operating System Interleave the execution of several processes to maximize processor utilization while providing

#include <iostream>#include <string>#include <sys/types.h>#include <unistd.h>using namespace std;

int globalVariable = 2;

main(){

string sIdentifier; int iStackVariable = 20;

pid_t pID = fork();

if (pID == 0) // child {

// Code only executed by child process sIdentifier = "Child Process: "; globalVariable++; iStackVariable++;

} else if (pID < 0) // failed to fork {

cerr << "Failed to fork" << endl; exit(1); // Throw exception

} else // parent {

// Code only executed by parent process sIdentifier = "Parent Process:";

}

// Code executed by both parent and child. cout << sIdentifier; cout << " Global variable: " << globalVariable; cout << " Stack variable: " << iStackVariable << endl;

}

Page 15: Process Control. Major Requirements of an Operating System Interleave the execution of several processes to maximize processor utilization while providing

Potential PitfallsPotential Pitfalls

Unintended File SharingUnintended File Sharing– Child process is a copy of parentChild process is a copy of parent– Includes files and other OS structuresIncludes files and other OS structures– Intermixed outputIntermixed output– File close on terminationFile close on termination

Race conditionsRace conditions– Each process is scheduled independentlyEach process is scheduled independently

Page 16: Process Control. Major Requirements of an Operating System Interleave the execution of several processes to maximize processor utilization while providing

ExecExec

Fork creates a copy of the parentFork creates a copy of the parent

Use exec() to launch another programUse exec() to launch another program– Initiate a program from within a programInitiate a program from within a program– Transforms the calling process into a new Transforms the calling process into a new

processprocess

Family of functionsFamily of functions– execl, execlp, execle, execv, execvp, execvPexecl, execlp, execle, execv, execvp, execvP– Front ends to the function execve Front ends to the function execve

Page 17: Process Control. Major Requirements of an Operating System Interleave the execution of several processes to maximize processor utilization while providing

execveexecve

Executes a process in an environment Executes a process in an environment which it assignswhich it assignsProcess arguments and the environment Process arguments and the environment are passed as null terminated arrays of are passed as null terminated arrays of character pointerscharacter pointers– char *env[] = {“USER=qos”,”PATH=/usr/bin:/bin”, (char *)0 };char *env[] = {“USER=qos”,”PATH=/usr/bin:/bin”, (char *)0 };– char *args[] = {“/bin/someprog”, “-r”, “-verbose”, (char *)0 };char *args[] = {“/bin/someprog”, “-r”, “-verbose”, (char *)0 };

– execve(args[0], args, env);execve(args[0], args, env);

Page 18: Process Control. Major Requirements of an Operating System Interleave the execution of several processes to maximize processor utilization while providing

execl and execlpexecl and execlp

Creates a new program in the same Creates a new program in the same environment environment

execl requires a fully qualified pathexecl requires a fully qualified path

execlp will use the environment variable execlp will use the environment variable PATH to search for the filePATH to search for the file

Takes a null terminated list of arguments Takes a null terminated list of arguments

Page 19: Process Control. Major Requirements of an Operating System Interleave the execution of several processes to maximize processor utilization while providing

execv and execvpexecv and execvp

Same as execl Same as execl – Arguments are passed as a null terminated Arguments are passed as a null terminated

array of character pointersarray of character pointers

Page 20: Process Control. Major Requirements of an Operating System Interleave the execution of several processes to maximize processor utilization while providing

#include <sys/types.h>

#include <unistd.h>

int pid;int status = 0;

pid = fork();if (pid != 0) {

/* parent */…..pid = wait(&status);

} else {

/* child */// Allocate and fill in argv and envp

//execve(const char *filename, char *const argv [], char *const envp[]);execve(argv[0], argv, envp);

// exec shouldn’t return return(ERROR);

}

Page 21: Process Control. Major Requirements of an Operating System Interleave the execution of several processes to maximize processor utilization while providing

Setting up the environmentSetting up the environment

// Set up the environment variable arrayenv = (char **)malloc((headerLines.size() + 1) * sizeof(char *));for (i = 0; i < headerLines.size(); i++){

env[i] = (char *)malloc(headerLength * sizeof(char));strcpy(env[i], headerLines[i]);if (strstr(env[i], "CONTENT_LENGTH")){

sscanf(env[i], "CONTENT_LENGTH=%d", &contentLength);//fprintf(stderr, "Scanned CONTENT_LENGTH is %d\n", contentLength);

}//fprintf(stderr, "Header --> [%s]\n", env[i]);

}env[i] = NULL;