Post on 10-Apr-2018
8/8/2019 OS Process Lab
1/22
System ProgrammingSystem Programming
ProcessProcess
8/8/2019 OS Process Lab
2/22
IntroductionIntroduction
If you have two terminal windows showing onIf you have two terminal windows showing onyour screen, then you are probably runningyour screen, then you are probably running
the same terminal program twicethe same terminal program twiceyou haveyou havetwo terminal processes.two terminal processes.
Each terminal window is probably running aEach terminal window is probably running ashell; each running shell is another process.shell; each running shell is another process.
When you invoke a command from a shell,When you invoke a command from a shell,the corresponding program is executed in athe corresponding program is executed in anew process; the shell process resumes whennew process; the shell process resumes whenthat process completes.that process completes.
8/8/2019 OS Process Lab
3/22
What Is a Process?What Is a Process?
Aprocess is an instance of an executingAprocess is an instance of an executingprogram and also the operatingprogram and also the operatingsystem's basic scheduling unit.system's basic scheduling unit.
process is considered a runningprocess is considered a running
programprogram
8/8/2019 OS Process Lab
4/22
Process IDsProcess IDs
EachEach processprocess inin aa LinuxLinux systemsystem isis identifiedidentified bybyitsits uniqueunique processprocess ID,ID, sometimessometimes referredreferred toto
asas pidpid.. ProcessProcess IDsIDs areare 1616--bitbit numbersnumbers thatthatareare assignedassigned sequentiallysequentially byby LinuxLinux asas newnewprocessesprocesses areare createdcreated..
EveryEvery processprocess alsoalso hashas aa parent parent processprocess
(except(except thethe specialspecial initinit process)process)..Thus,Thus, youyoucancan thinkthink ofof thethe processesprocesses onon aa LinuxLinux systemsystemasas arrangedarranged inin aa tree,tree, withwith thethe initinit processprocess atatitsits rootroot.. TheThe parentparent processprocess ID,ID, oror ppidppid,, isis
simplysimply thethe processprocess IDID ofof thethe processsprocesss parentparent..
8/8/2019 OS Process Lab
5/22
Element of ProcessElement of Process
The program's current context, which is theThe program's current context, which is theprogram's current execution statusprogram's current execution status
The program's current working directoryThe program's current working directory The files and directories to which theThe files and directories to which the
program has accessprogram has access
The program's credentials or access rights,The program's credentials or access rights,
such as its file mode and ownershipsuch as its file mode and ownership The memory and other system resourcesThe memory and other system resources
allocated to the processallocated to the process
8/8/2019 OS Process Lab
6/22
Viewing Active ProcessesViewing Active Processes
TheThe psps commandcommand displaysdisplays thethe processesprocesses thatthatareare runningrunning onon youryour systemsystem..
By default, invokingBy default, invoking psps displays the processesdisplays the processescontrolled by the terminal or terminal windowcontrolled by the terminal or terminal windowin whichin which psps is invokedis invoked..
Example:Example:
%% psps
PID TTY TIME CMDPID TTY TIME CMD
21693 pts/8 00:00:00 bash21693 pts/8 00:00:00 bash
21694 pts/8 00:00:0021694 pts/8 00:00:00 psps
8/8/2019 OS Process Lab
7/22
Viewing Active ProcessesViewing Active Processes
This invocation ofThis invocation of psps shows twoshows two rocesses.Therocesses.Thefirst, bash, is the shell running on thisfirst, bash, is the shell running on this
terminal. The second is the running instanceterminal. The second is the running instanceof theof the psps program itself.program itself.
The first column, labeled PID, displays theThe first column, labeled PID, displays theprocess ID of each.process ID of each.
8/8/2019 OS Process Lab
8/22
Viewing Active ProcessesViewing Active Processes
Example:Example:
%% psps --ee --oo pid,ppid,commandpid,ppid,command
TheThe --e option instructse option instructs psps to display allto display allprocesses running on the system. Theprocesses running on the system. The --oopid,ppid,commandpid,ppid,command option tellsoption tells psps whatwhatinformation to show about each processinformation to show about each processinin
this case, the process ID, the parent processthis case, the process ID, the parent processID, and the command running in this process.ID, and the command running in this process.
8/8/2019 OS Process Lab
9/22
Killing a ProcessKilling a Process
You can kill a running process with the killYou can kill a running process with the killcommand. Simply specify on the commandcommand. Simply specify on the command
line the process ID of the process to be killed.line the process ID of the process to be killed. Ex. %kill 21693Ex. %kill 21693
8/8/2019 OS Process Lab
10/22
Creating ProcessesCreating Processes
Two common techniques are used forTwo common techniques are used forcreating a new process.creating a new process.
The first is relatively simple but should beThe first is relatively simple but should beused sparingly because it is inefficient and hasused sparingly because it is inefficient and hasconsiderably security risks.considerably security risks.
The second technique is more complex butThe second technique is more complex but
provides greater flexibility, speed, andprovides greater flexibility, speed, andsecuritysecurity
8/8/2019 OS Process Lab
11/22
Method system()Method system()
The system function in the standard C libraryThe system function in the standard C libraryprovides an easy way to execute a commandprovides an easy way to execute a command
from within a program, much as if thefrom within a program, much as if thecommand had been typed into a shell.command had been typed into a shell.
system creates asystem creates a subprocesssubprocess running therunning thestandard Bourne shell (/bin/standard Bourne shell (/bin/shsh) and hands the) and hands the
command to that shell for executioncommand to that shell for execution
8/8/2019 OS Process Lab
12/22
ExampleExample
#include
intint main (){main (){
intint return_valuereturn_value;;return_valuereturn_value = system(= system(lsls l /);l /);
returnreturn return_valuereturn_value;;
}} The system function returns the exit status ofThe system function returns the exit status of
the shell command. If the shell itself cannotthe shell command. If the shell itself cannotbe run, system returnsbe run, system returns 127127; if another error; if another error
occurs, system returnsoccurs, system returns 11..
8/8/2019 OS Process Lab
13/22
Process IDsProcess IDs
When referring to process IDs in a C or C++When referring to process IDs in a C or C++program, always use theprogram, always use the pid_tpid_t typedeftypedef,,
which is defined in .Aprogramcan obtain the process ID of the process itscan obtain the process ID of the process itsrunning in with therunning in with the getpidgetpid()() system call, and itsystem call, and itcan obtain the process ID of its parentcan obtain the process ID of its parent
process with theprocess with the getppidgetppid()() system callsystem call
8/8/2019 OS Process Lab
14/22
Process IDs (Example)Process IDs (Example)
#include
#include
intint main ()main (){{
printfprintf (The process ID is %d(The process ID is %d\\n, (n, (intint)) getpidgetpid ());());
printfprintf (The parent process ID is %d(The parent process ID is %d\\n, (n, (intint)) getppidgetppid ());());
return 0;return 0;}}
8/8/2019 OS Process Lab
15/22
Process IDs (Example)Process IDs (Example)
Observe that if you invoke this program several times, aObserve that if you invoke this program several times, adifferent process ID is reported because each invocationdifferent process ID is reported because each invocationis in a new process. However, if you invoke it every timeis in a new process. However, if you invoke it every time
from the same shell, the parent process ID (that is, thefrom the same shell, the parent process ID (that is, theprocess ID of the shell process) is the sameprocess ID of the shell process) is the same
8/8/2019 OS Process Lab
16/22
Method fork()Method fork()
intint fork() turns a single process into 2fork() turns a single process into 2identical processes, known as theidentical processes, known as the parentparent
and theand the childchild.. On success, fork() returnsOn success, fork() returns 0 to the child0 to the child
processprocess andand returns the process ID of thereturns the process ID of thechild process to the parent processchild process to the parent process..
On failure, fork() returnsOn failure, fork() returns --1 to the parent1 to the parentprocess, setsprocess, sets errnoerrno to indicate the error,to indicate the error,and no child process is createdand no child process is created
8/8/2019 OS Process Lab
17/22
Method execl()Method execl()
execlexecl has 5 other related functionshas 5 other related functions -- see mansee manpages.pages.
execlexecl stands for execute and the l meansstands for execute and the l means?? It is defined by:It is defined by:
execlexecl(char *path, char *arg0,...,char *(char *path, char *arg0,...,char *argnargn, 0);, 0);
8/8/2019 OS Process Lab
18/22
ExampleExample
#include
void main(){void main(){
intint return_valuereturn_value;;
printfprintf(forking process);(forking process);
return_valuereturn_value=fork();=fork();
printfprintf(the process id = %d and return value = %d(the process id = %d and return value = %d\\n,getpidn,getpid(),(),return_valuereturn_value););
ex
ecl
ex
ecl(/bin/(/bin/
lsls,,lsls,,--l,0);
l,0);
PrintfPrintf(this line is not printed(this line is not printed\\n);n);
}}
8/8/2019 OS Process Lab
19/22
Example 2Example 2 #include #include #include #include
int main(){
pid_t pid;pid=fork();if(pid < 0) {
fprintf(stderr, Fork Failed);
exit(-1);}else
if(pid==0){execlp(/bin/ls,ls,NULL);
}
else{wait(NULL);
printf(Child Complete);exit(0);
}return 0;
}
8/8/2019 OS Process Lab
20/22
Exercise 1Exercise 1
Write c program that create two child processWrite c program that create two child process
The first child process write Hello in fileThe first child process write Hello in file11.txt.txt
The second child process write World! InThe second child process write World! Infilefile22.txt.txt
The parent process show the content of twoThe parent process show the content of twofiles .files .
Hint: use system functionHint: use system function
8/8/2019 OS Process Lab
21/22
Exercise 2Exercise 2
Write c program that accept 4 argumentWrite c program that accept 4 argumentnumbers and create two child processnumbers and create two child process
The first child process sum first and secondThe first child process sum first and secondargumentargument
The second child process sum third and forthThe second child process sum third and forthargumentargument
The parent process sum the result of two childThe parent process sum the result of two childprocess and get average exit the programprocess and get average exit the program
Ex. ./average 3 5 2 6Ex. ./average 3 5 2 6
The average is 4The average is 4
8/8/2019 OS Process Lab
22/22
Project 1Project 1
WriteWrite cc programprogram thatthat multiplicitiesmultiplicities twotwo arrayarray((2222)) andand acceptaccept 22 argumentargument filefile(arr(arr11..txt,arrtxt,arr22..txt)txt) thethe firstfirst filefile containcontainnumbersnumbers ofof firstfirst arrayarray andand thethe secondsecond filefilecontaincontain numbersnumbers ofof thethe secondsecond arrayarray ,, thenthencreatecreate childchild processesprocesses thatthat multiplicitiesmultiplicities eacheachrowrow withwith correspondingcorresponding columncolumn inin secondsecond
arrayarray 22 33 44 66
11 44 ** 33 22
BonusBonus:: multiplicitionmultiplicition ofof (N(NN)N) arrayarray