Chap 4
Chap 4
Chap 4
Unix processes
Overview
1. 2. 3. 4. What is a Process? fork() exec() wait()
1. What is a Process?
A process is an executing program. A process:
$ cat file1 file2 &
Two processes:
$ ls | wc - l
Foreground/background processes
A program run using the ampersand operator & creates a background process. E.g.: bingsun2% back & otherwise it creates a foreground process. E.g.: bingsun2% back
7
Foreground/background processes
Only 1 foreground process for each session. Multiple background processes. Where are background processes used? All system daemons, long user processes, etc. e.g. printer-daemon process or mailer-daemon process. These processes are always running in background. Pine is foreground process.
8
Pointer to program code Pointer to data Memory for global vars Pointer to stack Memory for local vars Pointer to heap Dynamically allocated Execution priority Signal information
Process 1 (init)
getty
2. fork()
#include <sys/types.h> #include <unistd.h> pid_t fork( void );
Creates a child process by making a copy of the parent process --- an exact duplicate.
Implicitly specifies code, registers, stack, data, files
fork() as a diagram
Parent
pid = fork() Returns a new PID: e.g. pid == 5 Data Child pid == 0 Shared Program Data Copied
In the child: pid == 0; In the parent: pid == the process ID of the child. A program almost always uses this pid difference to do different things in the parent and child.
else { /* child */ for( i=0; I < 1000; i++ ) printf( CHILD %d\n, i ); } return 0; }
Possible Output
CHILD 0 CHILD 1 CHILD 2 PARENT PARENT PARENT PARENT CHILD 3 CHILD 4 PARENT 4 : 0 1 2 3
Things to Note
i is copied between parent and child.
The switching between the parent and child depends on many factors:
machine load, system process scheduling
3. exec()
Family of functions for replacing processs program with the one inside the exec() call. e.g.
#include <unistd.h> int execlp(char *file, char *arg0, char *arg1, ..., (char *)0); execlp(sort, sort, -n, foobar, (char *)0); Same as "sort -n foobar"
4. wait()
#include <sys/types.h> #include <sys/wait.h> pid_t wait(int *statloc);
Suspends calling process until child has finished. Returns the process ID of the terminated child if ok, -1 on error.
statloc
can be (int *)0 or a variable which will be bound to status info. about the child.
wait() Actions
A process that calls wait() can:
suspend (block) if all of its children are still running, or return immediately with the termination status of a child, or
return immediately with an error if there are no child processes.
continued
9. I/O redirection
The trick: you can change where the standard I/O streams are going/coming from after the fork but before the exec
dup2(3,1) 0 1 2 3 4
stdin
x.lis
x.lis