process control

27
Process Control Process identifiers Process creation fork and vfork wait and waitpid Race conditions exec functions system function

Upload: dileep2113

Post on 06-Nov-2015

226 views

Category:

Documents


1 download

DESCRIPTION

pocess control

TRANSCRIPT

  • Process ControlProcess identifiersProcess creationfork and vforkwait and waitpidRace conditionsexec functionssystem function

  • Process IdentifiersEvery process has a PIDUnique non negative integerPIDs are re-usedTwo special PIDs0 scheduler process. A.K.A. swapper. System process.1 init process. Parent of all other processes.

  • Process IdentifiersFunctionspid_t getpid(void);pid_t getppid(void);uid_t getuid(void);uid_t geteuid(void);gid_t getgid(void);gid_t getegid(void);Shell command ps

  • Process Creationfork functionUsed to create new processesEvery process except swapper and init are created with forkpid_t fork(void);Creates a copy of the current processReturns 0 in the childReturns the PID of the child in the parentReturns -1 on error

  • Process CreationChild process gets a copy of the parents data space, heap and stackText segment is sharedModern implementations use copy-on-write for data because a fork is often followed by an exec

  • Buffering and forkingBuffers are part of the data of the parent and will be copied to the childLine buffered vs fully buffered are flushed at different timesMay cause output of program to differ if its re-directed to a file instead of screen (changes from line buffered to fully buffered)

  • File SharingFile descriptors are copied from parent to childImportant that file offsets changed by child are updated for parent as wellSee Fig. 8.2 on page 214Normally the parent will wait on the child to finish or close the descriptors that the child will use (and child closes the ones parent will use)

  • Inherited PropertiesRUID RGID EUID EGID Supplementary GIDsProcess Group IDSession IDControlling terminalset-user-ID and set-group-ID flagsCurrent working directoryRoot directoryFile mode creation maskSignal mask and dispositionsclose-on-exec flag for any open file descriptorsEnvironmentAttached shared memory segmentMemory mappingsResource limits

  • DifferencesReturn value from forkProcess IDsDifferent parent process IDsChilds tms_utime tms_stime tms_cutime and tms_cstime values are zeroFile locks not inheritedPending alarms cleared for childPending signals for child set to empty set

  • When fork failsToo many processes in the systemToo many processes for the real user IDCHILD_MAX specifies the max number of processes per user

  • vforkCreates a new processes with the express purpose of exec-ing a new programNew child process runs in parents address space until exec or exit is calledvfork guarantees that the child will run before the parent until exec or exit call is reached

  • exit functionsNormal terminationReturn from mainCalling exit Calling _exit or _ExitAbnormal terminationCalling abortReceiving some signals

  • exit functionsSpecial casesOrphaned processIf the parent of a process terminates before it does, that process becomes an orphaninit becomes the parent of all orphaned processesZombie processChild terminates, but parent has not yet called the wait or waitpid function to retrieve its exit statusStatus of zombie processes shown as Z by the ps commandinit always calls wait or waitpid for its children, so orphaned processes never become zombies

  • wait and waitpidpid_t wait(int *status);pid_t waitpid(pid_t pid, int *status, int options);Both return the PID of the child or -1 on errorstatus will hold the return status of the child when the function returns.

  • wait and waitpid4 mutually exclusive macros for interpreting the status argumentWIFEXITED(status)WEXITSTATUS(status)WIFSIGNALED(status)WTERMSIG(status)WCOREDUMP(status)WIFSTOPPED(status)WSTOPSIG(status)WIFCONTINUED(status)

  • wait and waitpidoptions argument specifies the behavior of the parent. Can be zero or binary OR of the following constantsWNOHANG do not block for child to terminate. Function returns zero in this caseWUNTRACED retrieves the status information for the process of a child that has been stoppedWCONTINUED same as WUNTRACED, but for the specified child that is continued

  • wait and waitpidpid argument has different meanings depending on its valuepid > 0 wait on child whose PID == pidpid == -1 - waits for any child pid == 0 waits for any child where process group ID equals the calling process group IDpid < -1 - waits for any child where process group ID equals absolute value of pid

  • Advantages of waitpidCan wait for a specified processHas a non-blocking optionSupports job control with the options argument

  • Race ConditionsA race condition occurs when two or more processes are using the same resource with no synchronization. In this case, the result is dependant on the order in which the processes executeOften solved with use of signals and other mechanisms to be discussed later

  • exec Functions6 versions of execReplaces the program in a process with the binary image in a specified filePID remains the sameAll return -1 on error, no return on success

  • exec Functionsint execl(const char *path, const char *arg, ...);int execle(const char *path, const char *arg,..., char * const envp[]);int execv(const char *path, char *const argv[]);int execvp(const char *file, char *const argv[]);int execlp(const char *file, const char *arg, ...);

  • exec Functionsp uses filename parameter and searches the PATH for the executablev arguments to new program are contained in a vector (array of strings)l arguments to new program are contained in a list (separate parameters) with final entry being NULLe function takes a vector of environment values instead of using the current system environment

  • Changing UID and GIDint setuid(uid_t uid);int setgid(gid_t gid);Rules for setting the IDEUID = 0 then setuid sets RUID, EUID and set-user-ID to uidEUID != 0 but uid = RUID or set-user-ID then setuid sets EUID to uid. RUID and set-user-ID remain unchangedOtherwise, sets errno to EPERM (operation not permitted) and return -1

  • Changing Effective IDsint seteuid(uid_t euid);int setegid(gid_t egid);Sets only effective IDs, not real or saved

  • System Functionint system(const char *command);Executes a shell command string from within a programCauses a fork, exec and waitpidReturns-1 if fork failed127 if exec failedExit status of shell otherwise

  • User Identificationchar *getlogin(void);Returns a string containing the users login name or NULL on error

  • Process Timesclock_t times(struct tms *buf);struct tmsclock_t tms_utimeclock_t tms_stimeclock_t tms_cutimeclock_t tms_cstimeThe clock_t values are measured in secondsTo get clock ticks, find the clock ticks per second with sysconf(_SC_CLK_TCK);

    **

    Executable corresponding to init process lives in /etc/init (older versions of UNIX) or /sbin/init*pid_t getpid(void); - gets the current process IDpid_t getppid(void); - gets the parent process IDuid_t getuid(void); - gets the real user ID of processuid_t geteuid(void); - gets the effective user ID of processgid_t getgid(void); - gets the real group ID of processgid_t getegid(void); - gets the effective group ID of process

    ***

    printf(Hello World\n);fork();

    Gives a different output than:

    printf(Hello World);fork();

    Because the newline causes line buffered output to flush.

    Also, re-directing the output of the program to a file can change the output of some programs because it will be fully buffered instead of line buffered.****http://www.cs.uah.edu/~kkeen/CS590/examples/processcontrol/forkexample*

    vfork started with 2.9BSD and as of Version 3 of the Single UNIX Specification, is marked obsolete.

    http://www.cs.uah.edu/~kkeen/CS590/examples/processcontrol/vfork*

    All 3 forms of exit take an int parameter that is the exit status. This status can be retrieved by the parent process with the wait or waitpid functions (described later)

    Remember that _exit and _Exit do not run exit handlers*

    Everytime a process terminates, the Kernel checks to see if any active process was the child of the terminating process. If so, the parent of the child is set to 1 (init process)

    A zombie process is simply the left over book keeping from a process. The memory may already be released, and file identifiers closed long before wait or waitpid is called in the parent.*Requires

    We can pass in NULL for the status parameter if we dont care about the childs exit status

    *

    If WIFEXITED is true, then the process terminated normally and WEXITSTATUS will retrieve the low order 8 bits which we can use in a call to any of the exit functions

    WTERMSIG gives the signal number that caused the process to terminate

    ***http://www.cs.uah.edu/~kkeen/CS590/examples/processcontrol/waitpid*http://www.cs.uah.edu/~kkeen/CS590/examples/racecond***

    Note that the list functions must have NULL as their last parameter AND it must be typecast to a char*

    http://www.cs.uah.edu/~kkeen/CS590/examples/processcontrol/execexample*

    These require

    EUID = 0 means root effective permissions

    setgid works the same way*

    Requires

    Note that a processes with superuser privileges can not temporarily step down and then back up again using setuid because calling setuid with root permissions will set all 3 IDs. Instead, a process with root permissions can use this seteuid to temporarily step down and the saved set-user-ID will not be changed.**

    Requires

    An example of when this function might return NULL is the case of daemons that may not be connected to a terminal*

    Requires

    tms_utime - user CPU timetms_stime - system CPU timetms_cutime - user CPU time, terminated childrentms_cstime - system CPU time, terminated children

    Children times only for those that have been waited onWall clock time returned from function. Relative measure. Save and subtract difference to determine the change.