TDC368 UNIX and Network Programming Camelia Zlatea, PhD Email: czlatea @ cs . depaul . edu Week 2: UNIX process concepts
Mar 20, 2016
TDC368UNIX and Network Programming
Camelia Zlatea, PhDEmail: [email protected]
Week 2: UNIX process concepts
UNIX Network Programming – TDC368-901 Page 2Spring 2003
Course Outline
UNIX process concepts. Process control primitives
fork, exec, exit, wait, waitpid getpid, getppid library functions: system
UNIX Network Programming – TDC368-901 Page 3Spring 2003
UNIX basic commands
Changing password: – passwd
Information: – date – cal– who– man
Shells– program that handles user interactions– Bourne shell (sh); default prompt is dollar sign $– Korn shell (ksh); a superset of the Bourne shell– C shell (csh); developed at UC Berkeley, part of BSD version of
UNIX; default prompt is the percent sign %
File Manipulation:cat file - displays the content of filels - list a directorycd - change directorymkdir - create a new directoryrm file - delete filerm –r file - delete recursively a catalog
UNIX Network Programming – TDC368-901 Page 4Spring 2003
Processes Hierarchy
PID=0 swapper
PID=1 init
PID = x
gttyfork - by initexec gtty
init process activates a new process and executed a program called getty for each terminal port of the systems
getty:displays the login prompt at the assigned terminalwaits for user to type userIDexecute a new program called login
UNIX Network Programming – TDC368-901 Page 5Spring 2003
Processes Hierarchy
PID=0 swapper
PID=1 init
PID = x
login
fork - by initexec gttyexec login
login:displays the password prompt at the assigned terminalwaits for user to type passwordverifies userID and passwordexecutes the user default shell
UNIX Network Programming – TDC368-901 Page 6Spring 2003
Processes Hierarchy
PID=0 swapper
PID=1 init
PID = x
sh
sh:shell displays the prompt ( example $) and
is ready to accepts user commands
fork - by initexec gttyexec loginexec sh
UNIX Network Programming – TDC368-901 Page 7Spring 2003
Processes Hierarchy
PID=0 swapper
PID=1 init
PID = x
sh
PID = y
ls -lfork - by shexec ls
Example:a shell command is executed
fork - by initexec gttyexec loginexec sh
UNIX Network Programming – TDC368-901 Page 8Spring 2003
Shell Processes
Execution of a Shell command (will explain this in the next slides)– [fork] new process– [exec] command– [wait] shell waits for child process to terminate
Displaying process table (process status) (PID= process ID, TTY=terminal. TIME=duration the process is running,
COMMAND=name of the command…)– ps– ps –al
Sequential execution of processes using shell operator semicolon ;– ps ; ls
Timing a delaying of a process– sleep 20 --- delays the shell for 20 seconds– sleep 120 ; echo “I am awake!”
UNIX Network Programming – TDC368-901 Page 9Spring 2003
Background Processes
Shell does not wait for child process to complete Returns prompter immediately shell: [fork] [fork] [exec]
– shell child exits immediately after the second [fork], returns prompter– shell grand-child [exec] the command in background– it is adopted by process init– when user logout the background process is terminated
sleep 30 & (sleep 120 ; echo “I am awake!”)&
The command nohup causes the background process to be immune to terminating signals
nohup (sleep 120 ; echo “I am awake!”)& and then logout– the command process will continue execution in background– where is the echo output displayed, since the process is no longer
associated with any terminal?» The output is automatically save to nohup.out
UNIX Network Programming – TDC368-901 Page 10Spring 2003
Terminating a process
The kill command– kill command sends a termination signal to the specified process, with the
given PID– Signal is an asynchronous event (identified by an integer number)– Signals 1 to 15 are implemented on the majority of UNIX systems– SIGTERM = 15 (normal termination)– SIGKILL=9 (forced termination)
Example:– sleep 30&– ps
PID TTY TIME COMMAND24000 tty001 0:05 csh24001 tty001 0:00 sleep 3024002 tty001 0:02 ps
– kill –9 24001
UNIX Network Programming – TDC368-901 Page 11Spring 2003
Process - system support Fork system call Process states Exec system call Exit function Background processes Parent-Child Synchronization (wait)
UNIX Processes
UNIX Network Programming – TDC368-901 Page 12Spring 2003
pid_t pid;pid = fork();if (pid ==-1)
{ /* fork failure, no more entries in process table*/ }
elseif (pid==0){
/*child process*/ }
else { /* parent process */ }
Fork - System Call
UNIX Network Programming – TDC368-901 Page 13Spring 2003
Fork - System Call
The user process calls fork(); Store system call parameters
– arguments, return address, local variables) into the user stack. Call corresponding kernel service
– execution of a trap instruction In kernel space save:
– parameters, return address and local variables for kernel routine Execute kernel routine Normal Return
– cleans-up kernel stack– switch from kernel to user mode
UNIX Network Programming – TDC368-901 Page 14Spring 2003
Fork - System Call
Successful return from system call: parent and child processes:
– share same text segment– identical data segments– identical user & kernel stack segments– same user structure
parent normal return – restores return address from user stack
child “pseudo return”– restores same return address as the parent from its user stack
UNIX Network Programming – TDC368-901 Page 15Spring 2003
Parent Process
Child Process
File Table
I-node Table
textdatastack
textdatastack
Open FilesCurrent Directory
Open FilesCurrent Directory
UNIX Network Programming – TDC368-901 Page 16Spring 2003
Process States
Initiated - fork() Ready-to-Run
– in ready queue for CPU access Running
– process quantum Blocked
– sleep(n); /* deterministic delay */– pause(); /* non-deterministic delay */
Terminated– exit(int status);
Shell command: ps [options]
UNIX Network Programming – TDC368-901 Page 17Spring 2003
Process Model
New
Ready
Blocked/Suspended
RunningUser Mode
Terminated
exitsleep
wakeup
dispatch
created
QuantumExpired
RunningKernel Mode
System Call
InterruptReturn
InterruptInterrupt return
Zombie
UNIX Network Programming – TDC368-901 Page 18Spring 2003
Process Image Map
Proc. n
Proc. 1 Process ImageProcess Table
Text/Code Segment
Data Segment
Stack Segment
Process Control Block
UNIX Network Programming – TDC368-901 Page 19Spring 2003
Process Memory Map
High Address
System Memory Map
process 0process 1.....
process i....
program text segmentinitialized static data
uninitialized static data
heap
stack
argc argv; environment
System Process Info.System Stack
User addressablearea
Systemaddressablearea
Low Address
UNIX Data Structuresu area
BuffersKernel code
Low level device drivers
UNIX Network Programming – TDC368-901 Page 20Spring 2003
User mode– processes in use mode can access their own instructions and data;
NOT kernel or other process’s code or data Kernel mode
– process can access system(kernel) code and data and user addresses– Kernel is part of each process– Kernel executes on behalf of the process
P1 P2 P3 P4
Kernel Mode
User Mode
K K
U U
OSHW
UNIX Network Programming – TDC368-901 Page 21Spring 2003
Process information
#include <sys/types.h>#include <unistd.h>
pid_t getpid(void);/* get current process ID */
pid_t getppid(void);/* get ID of the parent of the process */
UNIX Network Programming – TDC368-901 Page 22Spring 2003
pid_t pid;static int x;
x=1;pid = fork();if (pid < 0 ) {perror(“fork failure”)}else if (pid==0)
x++; else
x--;printf(“process %d: x=%d\n”, getpid(), x);
What value(s) are printed for variable x?
UNIX Network Programming – TDC368-901 Page 23Spring 2003
#include <stdio.h>#include <sys/types.h>#include <unistd.h>
void main(void) {fork(); printf(“A\n”);fork(); printf(“B\n”);fork(); printf(“C\n”);
}
Comment on the above program output.
UNIX Network Programming – TDC368-901 Page 24Spring 2003
#include <stdio.h>#include <sys/types.h>#include <unistd.h>
void main(void) {int i;for (i=1; i<=3; i++) {
fork(); printf(“PID=%d i=%d\n”, getpid(), i);
}printf(“PID=%d i=%d\n”, getpid(), i);
}
Comment on the above program output.
UNIX Network Programming – TDC368-901 Page 25Spring 2003
#include <stdio.h>#include <sys/types.h>#include <unistd.h>
void main(void) {int i;for (i=1; i<=3; i++) {
if (fork()==0) break; printf(“PID=%d i=%d\n”, getpid(), i);
}printf(“PID=%d i=%d\n”, getpid(), i);
}
Comment on the above program output.
UNIX Network Programming – TDC368-901 Page 26Spring 2003
#include <stdio.h>#include <sys/types.h>#include <unistd.h>
void main(void) {int i;for (i=1; i<==3; i++) {
if (fork()>0) break; printf(“PID=%d i=%d\n”, getpid(), i);
}printf(“PID=%d i=%d\n”, getpid(), i);
}
Comment on the above program output.
UNIX Network Programming – TDC368-901 Page 27Spring 2003
#include <stdio.h>#include <sys/types.h>#include <unistd.h>#include <string.h>
void main(void) {static char buf[2];
if (fork()==0) strcpy(buf,”A\n”);else strcpy(buf,”B\n”);sleep(10); write(1,buf,sizeof(buf));
}
Comment on the above program execution
UNIX Network Programming – TDC368-901 Page 28Spring 2003
Exec - System Call
#include <unistd.h>int execl(const char *file, const char arg0, .. , const argn);int execv(const char *file, char *argv[]);
the process executes the the binary code from file if failure return -1 if success does not return
UNIX Network Programming – TDC368-901 Page 29Spring 2003
File test1.c
#include <stdio.h>#include <sys/types.h>#include <unistd.h>void main(void) { int i;for (i=1; i<=3;i++)
if (fork()==0) { /* process child */execv(“/bin/ps”,”ps -el”);
}else { /* process partent */
printf(“Parent: %d\n”,getpid());}
} %cc -o test1 test1.c % test1
UNIX Network Programming – TDC368-901 Page 30Spring 2003
File test2.c
#include <stdio.h>#include <sys/types.h>#include <unistd.h>void main(void) {int i;for (i=1; i<=3;i++)
if (fork()==0) { /* process child */execv(“child”,”child”);
}else { /* process partent */
printf(“Parent: %d\n”,getpid());}
}
%cc -o test2 test2.c
UNIX Network Programming – TDC368-901 Page 31Spring 2003
File child.c
#include <stdio.h>#include <sys/types.h>#include <unistd.h>void main(void) {pid_t pid;
printf(“Parent: %d\n”,getpid());sleep(30);
}
%cc -o test2 test2.c%cc -o child child.c%test2
UNIX Network Programming – TDC368-901 Page 32Spring 2003
Exit - Function Call
#include <stdlib.h>void exit(int status);
status - parameter returned to parent process status=0 - normal termination status# - abnormal termination Effects:
– close all open file descriptors– notifies the parent (by signal)– return status info to parent– if parent no longer exists then PPD:=1 (is adopted by
process init)
UNIX Network Programming – TDC368-901 Page 33Spring 2003
_exit - System Call
#include <unistd.h>void _exit(int status);
status - process exit status code status=0 - normal termination status#0 - abnormal termination Effects:
– terminates a process– closes all open file descriptors– De-allocates all process data and stack segment– process becomes a zombie (it is no longer scheduled to run)– init process clean up process table slot
UNIX Network Programming – TDC368-901 Page 34Spring 2003
_exit - System Call
#include <iostream.h>#include <unistd.h>int main() {cout << "Test for _exit" << endl;
_exit(0);
return 0;
}% CC -o test test.c; testTest for _exit% echo $status0
UNIX Network Programming – TDC368-901 Page 35Spring 2003
Wait - System Call
#include <sys/types.h>#include <sys/wait.h>pid_t wait(int *status);
returns -,1 if failure (check errno)– no unwaited-for child process– interrupt signal
returns the child PID, is success synchronization:
– parent waits for a child to terminate– if more child-processes, waits for any
UNIX Network Programming – TDC368-901 Page 36Spring 2003
Waitpid - System Call
#include <sys/types.h>#include <sys/wait.h>pid_t waitpid(pid_t p, int *status, int opt);
Return value - a child process ID or -1 Argument pid_t p - a child PID
-1 waits for any child (same as wait) 0 waits for any child in same group w/ parent >0 waits for child process with this PID=p<-1 waits for any child with GID = |p|
UNIX Network Programming – TDC368-901 Page 37Spring 2003
Waitpid - System Call
#include <sys/types.h>#include <sys/wait.h>pid_t waitpid(pid_t p, int *status, int opt);
Options valuesWNOHANG - do not block if status cannot be obtained
WNOWAIT - keep process in wait statusWUNTRACED - wait any stopped child process
UNIX Network Programming – TDC368-901 Page 38Spring 2003
#include <stdio.h>#include <sys/types.h>#include <unistd.h>#include <sys/wait.h>void main(void) {pid_t pid; int i, status;for (i=1; i<=3;i++)
if (fork()==0) execv(“child”,”child”);else
printf(“Parent: %d\n”,getpid());while (pid = wait(&status) && pid!=-1)
printf(“Child %d is done\n”,getpid());exit(0);}
Parent-Child Process Synchronization
UNIX Network Programming – TDC368-901 Page 39Spring 2003
#include <stdio.h>#include <sys/types.h>#include <unistd.h>#include <sys/wait.h>void main(void) {pid_t pid[3], p; int i, status;for (i=0; i<=3;i++)
if ((pid[i]=fork())==0) execv(“child”,”child”);else printf(“Parent: %d\n”,getpid());
for(i=0;(p=waitpid(pid[i], &status,0)&&p!=-1;i++) if (p!=-1) && (errno==EINTR) printf(“Signal Caught: %s\n”,strerrno(errno));
exit(0);}
Parent-Child Process synchronization (by priorities)
UNIX Network Programming – TDC368-901 Page 40Spring 2003
#include <stdlib.h> int system(const char* cmd);
“system” function
User program:system(“ps -e”);
System calls actions:fork();//process creation serviceexecl(“/bin/ps”, “ps -e”);//code execution
Executable Programs
Library SystemFunctions Calls
Kernel
Hardware