Processes Wait, Exec. and ThreadsAdministrativeOverviewScheduling vs Dispatcher?Wait FunctionWaiting for a child to finish – C ManualWaiting for a child to finish: RR:72Wait for all children that have finishedDead children may become zombiesZombie RemovalWhat happensStatus Values for wait(int *stat_loc)Simple example (without checking EINTR)Typical process creation code (RR:74)Results from running programexec() FunctionExec ExampleBackground Processes and DaemonsDaemonsPowerPoint PresentationSlide 21Review: threads vs. processes (created with fork)Thread componentsSlide 24Creating a ThreadNormal function callThreaded function callThreaded Function Call DetailAn ExamplePthread Operationspthread_* return raluesSummaryCS 241 Spring 2007System Programming 01/14/19 CS241 © 2006 LA, RHC and YZ, All Rights Reserved1Processes Wait, Exec. and ThreadsLawrence AngraveLecture 7 , 1/31/072AdministrativeThis week SMP1, 2*Self Assessment Week 2 Lecture Quiz FridayDiscussion SectionsChallenge #1 & Challenge #2Reminder:RR: Ch 2[21-56] Ch 3[60-77]S: Ch 3[106-126] Read S:157-173,194-1973OverviewProcessesSchedulingWaitExecEnvironmentProcesses vs Threads4Scheduling vs Dispatcher?Scheduler decides which process to run nextDispatcher gives control to the next process selected by the schedulerSwitching process context Switching to user modeJumping to the proper location in the user program to restart that program5Wait Functionwait function allows parent process to wait (block) until child finisheswait function causes the caller to suspend execution until child’s status is availablewaitpid function allows a parent to wait for a particular childerrno causeECHILD Caller has no unwaited-for childredEINTR Function was interrupted by signal EINVAL Options parameter of waitpid was invalid6Waiting for a child to finish – C Manual#include <errno.h>#include <sys/wait.h>pid_t childpid; childpid = wait(NULL);if (childpid != -1) printf(“waited for child with pid %ld\n”, childpid);7Waiting for a child to finish: RR:72#include <errno.h>#include <sys/wait.h>pid_t r_wait(int *stat_loc) { int retval; while (((retval = wait(stat_loc)) == -1) && (errno == EINTR)) ; return retval;}•Restarts wait if interrupted by a signal•Part of Restart library in RR, Appendix B8Wait for all children that have finishedpid_t childpid;while (childpid = waitpid(-1, NULL, WNOHANG)) { if ((childpid == -1) && (errno != EINTR)) break;} // keep waitingWait for any child of current processWaitpid returns 0 to report there are possible unwaited-for children but their status is not availableRestart waitpid if function interrupted by signal or successfully waited for child9Dead children may become zombiesWhen a process terminates but its parent does not wait for it?Zombie (pid entry remains in system process table)Zombies unlike orphans do not consume many resources.10ZombieRemovalProfessional code installs signal handler for signal SIGCHLD … which issues a wait() call11What happensWhen the parent process terminates first?“Child is orphaned”Child is “re-parented” to init processChild continues to consume resourcesinit process (id=1) waits for children12Status Values for wait(int *stat_loc)The following macros are available for checking the return status of a child: #include <sys/wait.h> WIFEXITED(int stat_val) WEXITSTATUS(int stat_val) WIFSIGNALED(int stat_val) WTERMSIG(int stat_val) WIFSTOPPED(int stat_val) WSTOPSIG(int stat_val) They are used in pairs.If WIFEXITED returns true, the child executed normally and the return status (at most 8 bits) can be gotten with WEXITSTATUS.13Simple example (without checking EINTR) int status; childpid = wait(&status); if (childpid == -1) perror("Failed to wait for child"); else if (WIFEXITED(status) && 0==WEXITSTATUS(status)) printf(“Child terminated normally”);14Typical process creation code (RR:74)#include <stdio.h>#include <unistd.h>#include <sys/types.h>#include <sys/wait.h>int main (void) { pid_t childpid; /* set up signal handlers here ... */ childpid = fork(); if (childpid == -1) { perror("Failed to fork");return 1;} if (childpid == 0) fprintf(stderr, "I am child %ld\n", (long)getpid()); else if (wait(NULL) != childpid) fprintf(stderr, "A signal must have interrupted the wait!\n"); else fprintf(stderr, "I am parent %ld with child %ld\n", (long)getpid(), (long)childpid);return 0;}15Results from running program6 Possible forms of output!!!Fork failsParent catches signal after child executes fprintf but before child returnsParent catches signal after child terminates and wait returns successfullyParent catches signal between time child terminates and wait returnsParent catches signal before child executes fprintf and parent fprintf happens firstParent catches signal before child executes fprintf and child executes fprintf first16exec() Function Exec function allows child process to execute code that is different from that of parentExec family of functions provides a facility for overlaying the process image of the calling process with a new image. Exec functions return -1 and sets errno if unsuccessful… see Discussion Section slides & MP17Exec Example#include <stdio.h>#include <unistd.h>#include <sys/types.h>#include <sys/wait.h>int main (void) { pid_t childpid; childpid = fork(); if (childpid == -1) { perror("Failed to fork"); return 1; } if (childpid == 0) { /*child code*/ execl(“/bin/ls”, “ls”, “-l”, NULL); perror(“Child failed to exec ls”); return 1; } if (wait(NULL) != childpid) { /* parent code */ perror(“Parent failed to wait due to signal or error”); return 1; }return 0;}Argv[0] is program name so need ls in parameters18Background Processes and DaemonsShell – command interpreter creates background processes if line ends with &When shell creates a background process, it does not wait for the process to complete before issuing a prompt and accepting another commandCtrl-C does not terminate background processDaemon is a background process that normally runs indefinitely19DaemonsNot connected to a terminal (tty)Create logs in /var/log/Parent process “forks, disconnects tty and dies” so they are orphansEvent drivenExamples: ftpd, sshd, pageout daemon, httpd,mysqldSpecial privileges & access rights to hardware Execute as root or with a specific daemon useridA target for buffer overflow/Denial of Service
View Full Document