unix processes operating systems. the process id unix identifies each process with a unique integer...

Post on 24-Jan-2016

223 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

TRANSCRIPT

Unix ProcessesUnix ProcessesUnix ProcessesUnix Processes

operatingsystems

The Process IDThe Process IDThe Process IDThe Process ID

Unix identifies each process with a unique integer called a process ID.

The process that executes the request for creating a process is called the parent of the process.

The created process is called the child process.

Unix identifies each process with a unique integer called a process ID.

The process that executes the request for creating a process is called the parent of the process.

The created process is called the child process.

operatingsystems

Getting the process IDGetting the process IDGetting the process IDGetting the process ID

#include <stdio.h>#include <sys/types.h>#include <unistd.h>

int main ( ){ printf(“Process ID: %ld\n”, (long)getpid()); printf(“Parent process ID: %ld\n”, (long)getppid()); printf(“Process owner ID: %ld\n”, (long)getuid()); exit (0);}

ex1.c

operatingsystems

Process TerminationProcess TerminationProcess TerminationProcess Termination

Normal Terminationreturn from maincalling exitcalling _exit

Abnormal Terminationcalling abortterminated by a signal

Normal Terminationreturn from maincalling exitcalling _exit

Abnormal Terminationcalling abortterminated by a signal

calls exit

cleans up, closes all files

leaves files open, does not flush buffers

operatingsystems

atexit( ) functionatexit( ) functionatexit( ) functionatexit( ) function

ANSI C allows us to register up to 32 functions that areautomatically called by exit( ).

int atexit (void (*func) (void));

operatingsystems

C start-uproutine

main( )

userfunctions

Kernel

exit( )

I/Ocleanup

exit handler

exit handler

exec

call

callreturn

return

_exit

_exit

_exit

call & return

call & return

call & re

turn

User Process

More Process More Process TerminationTermination

More Process More Process TerminationTermination

When a process terminates, the operating system de-allocates the resources held by the process, and notifies other processes of its demise.

When a process exits, its orphaned children are adopted by the init* process. If it’s parent process is not waiting for it when it terminates, it becomes a zombie process.

operatingsystems

* launchd on OS-X (do ps –ax)

Process Creation using forkProcess Creation using forkProcess Creation using forkProcess Creation using forkmakes a copy of the parent’s system image and begins executing at the current instruction

child process gets a copy of the parent’s data space, heap and stack. They do not share memory!

The fork() call returns 0 to the child process, and the pid of the child to the parent process.

Whether the parent or the child executes first, once the child is created, depends upon the scheduling algorithm used by the kernel.

makes a copy of the parent’s system image and begins executing at the current instruction

child process gets a copy of the parent’s data space, heap and stack. They do not share memory!

The fork() call returns 0 to the child process, and the pid of the child to the parent process.

Whether the parent or the child executes first, once the child is created, depends upon the scheduling algorithm used by the kernel.

operatingsystems

Children Also Children Also InheritInheritChildren Also Children Also InheritInherituser and group IDscontrolling terminalcurrent working directoryroot directoryfile mode creation masksall open file descriptorssignal mask and dispositionsenvironmentattached shared memory segmentsresource limits

* Keep in mind that the child process does not share these, but has copies of its own that it inherits from the parent.

operatingsystems

*

Children Are Different Children Are Different Because …Because …

Children Are Different Children Are Different Because …Because …

They return a different value from fork

They have different process IDs

They have different parent process IDs

The child does not inherit file locks set by the parent

The set of pending signals for the child is set to the empty set

operatingsystems

Try the following code

#include <stdio.h>#include <unistd.h>

int main ( ){ int x;

x = 0; fork( ); x = 1; printf(“I am process %ld and my x value is %d\n”, (long)getpid( ), x);

return 0;}

What happened?

fork.c

Try the following code

#include <stdio.h>#include <unistd.h>

int main ( ){ int x;

x = 0; fork( ); x = 1; printf(“I am process %ld and my x value is %d\n”, (long)getpid( ), x);

return 0;}

At this point, there is one process.

Try the following code

#include <stdio.h>#include <unistd.h>

int main ( ){ int x;

x = 0; fork( ); x = 1; printf(“I am process %ld and my x value is %d\n”, (long)getpid( ), x);

return 0;}

A child process is created. It has the identicalcode and execution environment as the parent.

fork.c

Try the following code

#include <stdio.h>#include <unistd.h>

int main ( ){ int x;

x = 0; fork( ); x = 1; printf(“I am process %ld and my x value is %d\n”, (long)getpid( ), x);

return 0;}

Both processes now execute this code, changing its ownvalue of x, printing it, and exiting. The order dependson the scheduler.

Try the following code

#include <stdio.h>#include <unistd.h>

int main ( ){ int x;

x = 0; fork( ); x = 1; printf(“I am process %ld and my x value is %d\n”, (long)getpid( ), x);

return 0;}

Could the child process do something different fromthe parent process?

Yes ... test the return value of the fork( )

#include <stdio.h>#include <unistd.h>

int main ( ){ int x; pid_t childpid;

x = 0; childpid = fork( ); if ( childpid == -1) { perror(“failed to fork a new process”); return 1; }

fork1.c

if (childpid == 0) { x = 1; printf(“I am the child, my ID = %ld, my x = &d\n”, (long)getpid( ), x);}

else{ x = 2; printf(“I am the parent, my ID = %ld, my x = &d\n”, (long)getpid( ), x);}

return 0;}

What happened?

if (childpid == 0) { x = 1; printf(“I am the child, my ID = %ld, my x = &d\n”, (long)getpid( ), x);}

else{ x = 2; printf(“I am the parent, my ID = %ld, my x = &d\n”, (long)getpid( ), x);}

return 0;}

Both processes return here from the fork( ) call. However, the returnvalue to the parent is the pid of the child process. The return value tothe child is zero.

if (childpid == 0) { x = 1; printf(“I am the child, my ID = %ld, my x = &d\n”, (long)getpid( ), x);}

else{ x = 2; printf(“I am the parent, my ID = %ld, my x = &d\n”, (long)getpid( ), x);}

return 0;}

And ...the parent processexecutes this block

The child processexecutes this block,

What does the following code do?What does the following code do?What does the following code do?What does the following code do?

int main(int argc, char *argv[ ] ){ pid_t childpid = 0; int i, n;

n = atoi ( argv[1] ); for ( i = 1; i < n; i++) if (childpid = fork( ) ) break; fprintf(stderr, “i:%d process ID:%ld parent ID: %ld child ID %ld\n”, i, (long)getpid( ), (long)getppid( ), (long)childpid );

return 0;

operatingsystems

Creates a Creates a chainchain of of nn processesprocesses

Creates a Creates a chainchain of of nn processesprocesses

int main(int argc, char *argv[ ] ){ pid_t childpid = 0; int i, n;

n = atoi ( argv[1] ); for ( i = 1; i < n; i++) if (childpid = fork( ) ) break; fprintf(stderr, “i:%d process ID:%ld parent ID: %ld child ID %ld\n”, i, (long)getpid( ), (long)getppid( ), (long)childpid );

return 0;

process 1

process 2

process 3

process 4

a chainfor n = 4

the parent breaksout of the loop …the child continues through the loop onemore time, forks a newchild process and becomesthe parent for the nextiteration.

// non zero means I’m the parent

operatingsystems

chain.c

Creating a Creating a fanfan of child of child processesprocesses

Creating a Creating a fanfan of child of child processesprocesses

int main(int argc, char *argv[ ] ){ pid_t childpid = 0; int i, n;

n = atoi ( argv[1] ); for ( i = 1; i < n; i++) if (childpid = fork( ) <= 0 ) break; fprintf(stderr, “i:%d process ID:%ld parent ID: %ld child ID %ld\n”, i, (long)getpid( ), (long)getppid( ), (long)childpid );

return 0;

the child breaksout of the loop …the parent continues through the loop creatinga new child. This continuesuntil the loop conditionis satisfied.

parentprocess

child 1

child 2

child 3

operatingsystems

Run the example fan1.c a few times.

What do you notice about the output?

The order of the output is not in the order expected.This is because the parent just exits when it is done,the children may not have finished at this point. Theorder of execution depends upon how the processeswere scheduled to run. Can we make the parent waitto exit until all of its children have finished?

The wait( ) system callThe wait( ) system callThe wait( ) system callThe wait( ) system calloperatingsystems

When a fork ( ) occurs, both the parent and the child proceed with execution at the point of the fork.

If the parent wants to wait for the child to finish before continuing, it executes a wait( ). wait() causes the caller to stop until

the child terminates, orthe caller receives a signal

wait( ) returns immediately if there are no children executing

the return value of wait() is:the pid of the terminating child process, or-1 if there is no child to wait for or a signal occurred

errno = ECHILD indicates there was no childerrno = EINTR indicates there was a signal

#include <sys/types.h>#include <sys/wait.h>

pid_t wait (int *status);

returns -1 or pid of theterminating child. the return status of the child is

stored in status. Test with the macrosWIFEXITED - true if child terminated normallyWIFSIGNALED – true if child terminated abnormally because it failed to catch a signalWIFSTOPPED - true if a child is currently stopped

operatingsystems

operatingsystems Handling a wait that is interrupted by a signal

#include <errno.h>#include <sys/wait.h>

pid_t r_wait (int* status_loc){ int retval;

while ( ( (retval = wait(status_loc) ) == -1 && (errno == EINTR) ); return retval;}

if the wait returns because of a signal, stay in this loop

Fixing the fan program . . .

n = atoi(argv[1]);for (i = 1; i < n; i++) if ( (childpid = fork( ) ) <= 0) break;

while (r_wait(NULL) > 0); fprintf(stderr, ... )

see fan2.c

Fixing the fan program . . .

n = atoi(argv[1]);for (i = 1; i < n; i++) if ( (childpid = fork( ) ) <= 0) break;

while (r_wait(NULL) > 0); fprintf(stderr, ... )

see fan2.c

what happens if you replace the while statement with r_wait(NULL);

How many outputs are possible from this program?

int main ( ){ pid_t childpid;

childpid = fork( ); if (childpid == -1) { perror(“failed to fork”); return 1; } if (childpid == 0) fprintf(stderr, I am a child %ld\n”, (long)getpid( ) ); else if (wait(NULL) != childpid) fprintf(stderr, “A signal may have interrupted the wait\n”); else fprintf(stderr, I am a parent %ld\n”, (long)getpid( ) ); return 0;}

int main ( ){ pid_t childpid;

childpid = fork( ); if (childpid == -1) { perror(“failed to fork”); return 1; } if (childpid == 0) fprintf(stderr, I am a child %ld\n”, (long)getpid( ) ); else if (wait(NULL) != childpid) fprintf(stderr, “A signal may have interrupted the wait\n”); else fprintf(stderr, I am a parent %ld\n”, (long)getpid( ) ); return 0;}

1. The fork fails, the program will output “failed to fork”

int main ( ){ pid_t childpid;

childpid = fork( ); if (childpid == -1) { perror(“failed to fork”); return 1; } if (childpid == 0) fprintf(stderr, I am a child %ld\n”, (long)getpid( ) ); else if (wait(NULL) != childpid) fprintf(stderr, “A signal may have interrupted the wait\n”); else fprintf(stderr, I am a parent %ld\n”, (long)getpid( ) ); return 0;}

2. The child prints its message, but then the parent catches a signal before the child actually returns.

I am a child 3427

child code

parent code

a signal may have interrupted this call

int main ( ){ pid_t childpid;

childpid = fork( ); if (childpid == -1) { perror(“failed to fork”); return 1; } if (childpid == 0) fprintf(stderr, I am a child %ld\n”, (long)getpid( ) ); else if (wait(NULL) != childpid) fprintf(stderr, “A signal may have interrupted the wait\n”); else fprintf(stderr, I am a parent %ld\n”, (long)getpid( ) ); return 0;}

3. The child prints its message and returns. The wait returns normally

I am a child 3427 I am a parent 3424

child code

parent code

int main ( ){ pid_t childpid;

childpid = fork( ); if (childpid == -1) { perror(“failed to fork”); return 1; } if (childpid == 0) fprintf(stderr, I am a child %ld\n”, (long)getpid( ) ); else if (wait(NULL) != childpid) fprintf(stderr, “A signal may have interrupted the wait\n”); else fprintf(stderr, I am a parent %ld\n”, (long)getpid( ) ); return 0;}

4. The parent catches a signal and prints its “signal” message before the child prints its message.

A signal may have interrupted the call

parent code

child code

I am child 3427

int main ( ){ pid_t childpid;

childpid = fork( ); if (childpid == -1) { perror(“failed to fork”); return 1; } if (childpid == 0) fprintf(stderr, I am a child %ld\n”, (long)getpid( ) ); else if (wait(NULL) != childpid) fprintf(stderr, “A signal may have interrupted the wait\n”); else fprintf(stderr, I am a parent %ld\n”, (long)getpid( ) ); return 0;}

5. The parent catches a signal before the child prints its message, but it prints its “signal” message after the child prints.

parent code

child code

I am child 3427

A signal may have interrupted this call

Status Values

The status parameter of the wait( ) system call is an int*

If it is not NULL, the return status of the child is storedin the integer variable pointed to. The child status is returned by

return n exit (n)

A zero value indicates that the child process exited normally.

Keep in mind that the wait( ) system call blocksif there are any child processes executing. Whatif we want to see if a child process has terminated,but not block?

waitpidwaitpidwaitpidwaitpid

pid_t waitpid (pid_t pid, int *stat_loc, int options);

returns the pid of the childor -1 if there is an error, or 0 if there are children to be waited for, but none of them are done

the process to be waited for, or-1 if you want to wait for any childprocess to finish.

the interesting option isWNOHANG which causeswaitpid to return even if thereis there is no child for whichstatus is available.

operatingsystems

#include <sys/types>#include <sys/wait.h>#include <errno.h>

int status;pid_t waited_for_pid;

while (waited_for_pid = waitpid (-1, &status, WNOHANG) ) if ((waited_for_pid == -1) && (errno != EINTR) break;

this code segment waits for any child, without blocking,if there are no children with status available. It stays in theloop if the waitpid is interrupted by a signal.

operatingsystems

PollingPollingPollingPolling

A parent can wait for a child to finish by using the waitor waitpid calls.

However, what does a child do when it wants to wait for the parent to finish?

operatingsystems

while (getppid( ) != 1) sleep(1);

this type of code is called polling, and burns up cpu time

To avoid race conditions and polling, we use signals

why?

Zombie ProcessZombie ProcessZombie ProcessZombie Process

If a child process completes before its parent does,some vestige of the process has to hang around sothat the parent can determine its termination statuswith a wait( ).

This is called a zombie process.

operatingsystems

Orphan ProcessesOrphan ProcessesOrphan ProcessesOrphan Processes

What happens if the parent process exits before itschild process does. The child has to have a parent, soit is adopted by the init process.

operatingsystems

Reminder - forksReminder - forks are are usedused

Reminder - forksReminder - forks are are usedused

When a process wants to duplicate itself so that the parent and the child can execute different parts of theprogram simultaneously. This is common for serversoftware.

When a process wants to execute a different program.This is common for shells.

operatingsystems

exec( )exec( )exec( )exec( )operatingsystems

fork ( ) – creates a copy of the calling process.

exec ( ) – overlays the calling process with a new process.

Traditional approach is for the parent to fork( ) a new process, which then does an exec to overlay the process with the new program. The parent then stays around.

The exec copies a new executable into the process image. The program text, variables, stack, and the heap are overwritten.

Process A

program A

fork( );

rhtj,nn vio nlk;jh eahgjkfsdajhfk.ADFSkfdnkZXdfjklA:LDhlADjlkdfakJLc dsakl;naS fork( ) { exec( )‘ fdsnjhkjsd } hjfhksa}jkds,n,dsmkfljmhjsd fhjsdf‘jkfg { kjl;sdfdsf fdsjklsdf

Process B

program A

rhtj,nn vio nlk;jh eahgjkfsdajhfk.ADFSkfdnkZXdfjklA:LDhlADjlkdfakJLc dsakl;naS fork( ); { exec( );‘ fdsnjhkjsd } hjfhksa}jkds,n,dsmkfljmhjsd fhjsdf‘jkfg { kjl;sdfdsf fdsjklsdf

exec( )

rhtj,nn vio nlk;jh eahgjkfsdajhfk.ADFSkfdnkZXdfjklA:LDhlADjlkdfakJLc dsakl;naS hlhkasf jghji fhnjkjsdf fdsnjhkjsdfht9 hjfhksa}jkds,n,dsmkfljmhjsd fhjsdf‘jkfg { kjl;sdfdsf fdsjklsdf

program c

execl( )execl( )execl( )execl( )

This family of functions is useful when the number ofcommand line arguments is known at compile time

#include <unistd.h>

int execl(const char *path, const char *arg0, const char *arg1, … const char *argn, NULL);

path to the executable

first commandline argument

second commandline argument

final commandline argument

A NULLpointer

operatingsystems

ExampleExampleExampleExampleint main ( ){ pid_t childpid; int stat;

if ((childpid = fork() == -1) { perror(“Error in fork.”); exit(1); } else if (childpid == 0) { if (execl(“/bin/ls”, “ls”, “-l”, NULL) < 0) { perror(“Error in exec.”); exit(1); } } else if (childpid != wait(&stat)) { perror(“A Signal occurred before the child exited.”); exit(1); } return (0);}

This is child code. It replacesthe current process with /bin/ls

This is parent code.

operatingsystems

dols.c

Variations of execlVariations of execlVariations of execlVariations of execl

#include <unistd.h>

int execlp(const char *file, const char *arg0, const char *arg1, … , const char *argn, NULL);

int execle (const char *path, const char *arg0, const char *arg1, …, const char argn, NULL, char *const envp[]);

This variation uses the PATHvariable to locate the executable

This variation passes a pointer toan array of strings that holds a newenvironment for the command.

operatingsystems

execv( )execv( )This family of functions is used to pass command

line arguments to the new process

#include <unistd.h>

int execv(const char *path, char *const argv[]);

path to the executable

an argument array, just asif these had come from thecommand line . You have tobuild this!

execv also has execvp and execve variations.

operatingsystems

int main (int argc, char *argv[]){ pid_t childpid; int status; if ((childpid = fork()) == -1) { perror("The fork failed"); exit(1); } else if (childpid == 0) { if (execvp(argv[1], &argv[1]) <0) { perror("The exec failed"); exit(1); } } else { while(childpid != wait(&status)) { if ((childpid == -1) && (errno != EINTR)) break; } } return (0);}

execvp constructs thepathname using the PATH environment variable.

argv[0] is the first argumentwhen this command is executed,so &argv[1] points to the twotokens ls and -l

create the executable myexec.Then typing myexec ls –l willresult in this function calling ls -l

the parent waits for the child to terminate.

operatingsystems

A Shell A Shell A Shell A Shell

is a command interpreter which prompts for commands,reads the commands from standard input, forks children to execute the commands, and waits for the children to finish.

When you end a command with &, the shell creates thechild process, but does not wait for it to finish. The child is known as a background process.

operatingsystems

A daemon isA daemon isA daemon isA daemon is

a background process that runs indefinitely.

operatingsystems

Terminal Log-insTerminal Log-insTerminal Log-insTerminal Log-ins

/etc/ttys contains one line per terminal device

when the system is bootstrapped, the kernel createsprocess 1, the init process

init reads /etc/ttys and for each terminal device in the file,it forks a new process and execs the getty program

operatingsystems

* launchd on OS-X (do ps –ax)

*

init

initinit init. . .

fork (once per terminal)

getty getty getty

exec execexec

operatingsystems

getty opens a terminal device and issues a login message

When a user name is entered, getty execs login

login gets the password and checks to see if all is well

If it is, login changes to the user’s home directory, changes ownership of the terminal, initializes the environment, and execs the shell specified for the user.

operatingsystems

init

init

getty

exec

fork

login

exec

shell

exec

operatingsystems

Process GroupsProcess GroupsProcess GroupsProcess GroupsIn addition to having a process ID, each process belongs toa process group. A process group is a collection of oneor more processes.

operatingsystems

SessionSession

A session is a collection of one or more process groups.

An Example using An Example using redirectionredirection

An Example using An Example using redirectionredirection

This program exploits the fact that open filedescriptors are preserved across fork and exec calls.

operatingsystems

#include <stdio.h>#include <ctype.h>

int main( ){ int ch;

while ((ch = getchar( ) ) != EOF) { putchar(toupper(ch)); } exit(0);}

This program is written as a filter. It reads in text and convertsit to upper case.

upper

operatingsystems

upper.c

What if we want to invoke this filterfrom inside of a program?

operatingsystems

#include <unistd.h>#include <stdio.h>

int main ( int argc, char *argv[]){ char *filename;

filename = argv[1];

// now call freopen to open the file on standard input if (!freopen(filename, "r", stdin)) { printf("Could not re-direct file to stdin\n"); exit(1); }

// now exec the upper program execl( "./upper", "upper", 0);

// since the exec replaces the current program, the following // lines are not executed unless the exec fails. perror("could not exec ./upper"); exit(3);}

Closes the file descriptor for stdinThen re-opens the file as stdin

execupper.c

top related