1 / 55

Chapter 3: Processes

Chapter 3: Processes. Process Concept. Textbook uses the terms job and process almost interchangeably Process – a program in execution; process execution must progress in sequential fashion Consists of The program code, also called text section

karim
Download Presentation

Chapter 3: Processes

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 3: Processes

  2. Process Concept • Textbook uses the terms job and process almost interchangeably • Process – a program in execution; process execution must progress in sequential fashion • Consists of • The program code, also called text section • Current activity including programcounter, processor registers • Stackcontaining temporary data • Function parameters, return addresses, local variables • Data sectioncontaining global variables • Heapcontaining memory dynamically allocated during run time

  3. Process in Memory

  4. Process Concept (Cont.) • Program is passive entity stored on disk (executable file), process is active • Program becomes process when executable file loaded into memory • Execution of program started via GUI mouse clicks, command line entry of its name, etc • One program can be several processes • Consider multiple users executing the same program

  5. Process State • As a process executes, it changes state • new: The process is being created • running: Instructions are being executed • waiting: The process is waiting for some event to occur • ready: The process is waiting to be assigned to a processor • terminated: The process has finished execution

  6. Process Control Block (PCB) Information associated with each process (also called task control block) • Process state – running, waiting, etc • Program counter – location of instruction to next execute • CPU registers – contents of all process-centric registers • CPU scheduling information- priorities, scheduling queue pointers • Memory-management information – memory allocated to the process • Accounting information – CPU used, clock time elapsed since start, time limits • I/O status information – I/O devices allocated to process, list of open files

  7. Context Switch A CPU can execute one process at a time In a multiprogramming environment the CPU switches from one process to another for brief periods of time. When CPU switches to another process, the system must save the state of the old process and load the saved state for the new process via a context switch Context of a process represented in the PCB

  8. Context Switch Context-switch time is overhead; the system does no useful work while switching The more complex the OS and the PCB  the longer the context switch Time dependent on hardware support Some hardware provides multiple sets of registers per CPU  multiple contexts loaded at once

  9. CPU Switch From Process to Process

  10. Process Representation in Linux Represented by the C structure task_struct pid t_pid; /* process identifier */ long state; /* state of the process */ unsigned int time_slice /* scheduling information */ struct task_struct *parent; /* this process’s parent */ struct list_head children; /* this process’s children */ struct files_struct *files; /* list of open files */ struct mm_struct *mm; /* address space of this process */

  11. Process Scheduling • Maximize CPU use, quickly switch processes onto CPU for time sharing • Process scheduler selects among available processes for next execution on CPU • Maintains scheduling queues of processes • Job queue – set of all processes in the system • Ready queue – set of all processes residing in main memory, ready and waiting to execute • Device queues – set of processes waiting for an I/O device • Processes migrate among the various queues

  12. Ready Queue And Various I/O Device Queues

  13. Representation of Process Scheduling • Queueing diagram represents queues, resources, flows

  14. Schedulers • Short-term scheduler (or CPU scheduler) – selects which process should be executed next and allocates CPU • Sometimes the only scheduler in a system • Short-term scheduler is invoked frequently (milliseconds)  (must be fast) • Long-term scheduler (or job scheduler) – selects which processes should be brought into the ready queue • Long-term scheduler is invoked infrequently (seconds, minutes)  (may be slow) • The long-term scheduler controls the degree of multiprogramming (which processes are in memory) • Processes can be described as either: • I/O-bound process– spends more time doing I/O than computations, many short CPU bursts • CPU-bound process – spends more time doing computations; few very long CPU bursts • Long-term scheduler strives for good process mix

  15. Operations on Processes • System must provide mechanisms for: • process creation, • process termination, • and so on as detailed next

  16. Process Creation • Parentprocess create childrenprocesses, which, in turn create other processes, forming a tree of processes • Generally, process identified and managed via aprocess identifier (pid) • Resource sharing options • Parent and children share all resources • Children share subset of parent’s resources • Parent and child share no resources • Execution options • Parent and children execute concurrently • Parent waits until children terminate • Address space options • Child duplicate of parent (same program and data) • Child has a program loaded into it

  17. A typical tree of processes in Linux

  18. Process Control • To list the complete information for all active processes in the system • ps –ef • To list your processes • ps

  19. Process Control • When the shell has to wait for a process to finish before giving you another prompt, that process is in the foreground • A background process is one that runs independently of the parent shell • The shell doesn't have to wait for the process to finish • The shell gives you a prompt immediately and you can execute another command • To run a command in the background: • command& • The shell will display the job number and PID of the background process and then display the prompt • Any output of the background process that is sent to stdout will appear on the terminal, intermixed with the foregound process • you will probably want to redirect the process‘ output

  20. Process Control • When a process is in the background, you can't use <ctrl>c to stop it • Only foreground processes will recognize keyboard input • You must use the kill command • kill <pid> • If the kill command is ignored, then use the -9 option • kill -9 <pid> • We can control whether a process should continue in the foreground or background • From background to foreground • fg <job number> • From foreground to background • <ctrl>z to suspend the foreground process • bg to send it to the background • If a background process needs input, the shell will stop the job • You must then bring it to the foreground to enter the input

  21. Creating a process in UNIX • We need some mechanism to instruct the system to create a new process • fork system call • When fork( ) is used, the OS generates a copy of the calling process • The original process is the parent process • The copy is the child process • Execution in the two IDENTICAL processes continues from the point of the fork( ) • The child process inherits all variables, values, open files, current directory, environment variables, etc. from the parent • The child is assigned a unique PID • The parent's fork returns the child's PID • The child's fork returns 0 • There is no guarantee which process, parent or child, will enter the CPU first

  22. fork() pid = fork() if (pid!=0) { //parent code} else { // child code }

  23. fork() example: fork_ex1.c

  24. output > g++ -o ex1 fork_ex1.c > ./ex1 I am the original process with PID 25643 and PPID 25592. I am the parent process with PID 25643 and PPID 25592. my child's PID is 25644 PID 25643 terminates. I am the child process with PID 25644 and PPID 25643. PID 25644 terminates.

  25. getpid, getppid, getpgid, setpgid • pid_t getpid() • Returns the PID of the calling process • pid_t getppid() • Returns the calling process’ parent’s PID • If parent needs child processes’ PIDs they must be saved when the children are forked. • Process groups • Every process belongs to a group • The parent process is the process leader of all its children processes • The leader's pid will also be the process group id (PGID) • The PGID allows the OS to send signals to groups of processes • pid_t getpgid(pid_t pid); • Returns the process group ID of the process whose PID is equal to pid • Returns the process group ID of the calling process if pid is 0 • int setpgid(pid_t pid, pid_t pgid); • Sets the process group ID of the process with PID pid to pgid

  26. fork_ex2.c

  27. Output (with newline, output not buffered) > g++ -o ex2 fork_ex2.c > ./ex2 hee ha hee ho ha ha ha ho ho ho ho ho ho ho >

  28. Output without newline (buffered) • Buffer is flushed when full, or when file is closed. • newline forces flush to stdout • Buffers are inherited by child process • Output: heehahoheehahoheehahoheehahoheehahoheehahoheehahoheehaho

  29. Open files • Every process is given a file descriptor table • Every open file of a process is assigned an index into this table called the file descriptor • When a child process is forked, it receives a COPY of its parent's file descriptor table • This includes where the parent is in each open file • The file pointer offset • That is, the child starts reading from the same point • If one of them reads from a such an open file, the read/write pointer is advanced for both of them.

  30. Getting file Information • int stat(const char *filename, struct stat *buf) • int stat(int filedes, struct stat *buf) • Returns the information for the given filename/file descriptor in the stat struct • The stat struct: struct stat {       mode_t   st_mode;         /* Protection */       ino_t    st_ino;          /* Inode number */       dev_t    st_dev;          /* ID of device containing */                                 /* a directory entry for this file */       nlink_t  st_nlink;        /* Number of links */       uid_t    st_uid;          /* User ID of the file's owner */       gid_t    st_gid;          /* Group ID of the file's group */       off_t    st_size;         /* File size in bytes */       time_t   st_atime;        /* Time of last access */       time_t   st_mtime;        /* Time of last data modification */       time_t   st_ctime;        /* Time of last file status change */                                 /* Times measured in seconds since */                                 /* 00:00:00 UTC, Jan. 1, 1970 */       long     st_blksize;      /* Preferred I/O block size */       blkcnt_t st_blocks;       /* Number of 512 byte blocks allocated*/ }

  31. stat_ex.c #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> main(int argc, char *argv[]) { struct stat buff; if (argc > 1 ) { if (stat(argv[1], &buff) != -1) { printf("The size in bytes of %s is:", argv[1]); printf("%d\n", buff.st_size); } else { perror(argv[1]); return 1; } } else { printf("Usage: %s filename\n", argv[0]); return 2; } return 0; //successful }

  32. Handling error • When a system call or library function fails, it usually returns a -1 • It also assigns a value to an external variable errno • By examining errno, you can determine the cause of the failure • errno always contains the value of the last failed call • A list of error values, their defined constants, and a short explanation of the error can be found in /usr/include/sys/errno.h • To include this header file in your program, use #include <errno.h> • perror system call • Used to capture the description of any error • It takes one argument - a pointer to a char (string s) • It prints the string s followed by a colon and a blank, then an error message and a new line • See errno_ex.c

  33. Current Directory • char *getcwd(char *buf, size_t size); • The  getcwd() function (not system call) copies an absolute pathname of the current working directory to the array pointed to by buf, which is of length size. • If the current absolute path name would require a buffer longer than size elements, NULL  is returned, and errno is set to ERANGE • Going someplace new • int chdir(const char *path); • chdir changes the current directory to that specified in path. • What do you think happens when a child process executes a chdir - does this effect the parent?

  34. /*    Testing the chdir() function*/#include <stdio.h>#include <unistd.h>#include <sys/param.h>main( ){     int pid;     printf( "Before forking, my directory is: %s\n", getcwd(NULL, MAXPATHLEN+1) );     pid = fork();     if ( pid != 0 )     {          sleep( 5 );          printf( "Parent's directory is: %s\n", getcwd(NULL, MAXPATHLEN+1) );     }     else     {          chdir( "/usr/include" );          printf( "child's directory is: %s\n", getcwd(NULL, MAXPATHLEN+1) );     }}

  35. output • >a.outBefore forking, my directory is: /home/fatalay/CSC310child's directory is: /usr/includeParent's directory is: /home/fatalay/CSC310

  36. exec() • When you use the shell to run a command (say ls), the shell will execute fork( ) to get a new process running • How then does the shell get ls to run in the child process? • The child process is just a copy of the shell - which is certainly NOT the ls utility • Use an exec( ) system call or library function • During an exec the current process image is overlaid with the command image • The text, data, and stack segments are replaced with the new code • Signals that were being caught in the original process are reset to their default action • If successful, exec does NOT return since the original code is lost • The new program begins executing at main (if a C, C++, or Java program)

  37. exec family • 5 library functions • Execl, execlp, execv, execvp, execle • 1 system call • Execve • All library functions call the system call execve • execlp, execvp are the most commonly used.

  38. execl and execlp • execl library function • int execl(const char *path, const char *arg, ...); • path is the absolute or relative path name of the command • arg0 the name of the command • arg1 - argn are the null terminated strings representing arguments to the command • argn must be NULL • execlp library function • int execlp(const char *file, const char *arg, ...); • file is the absolute or relative path name of the command • PATH will be searched if the first character is not a /

  39. execv and execvp • execv library function • int execv(const char *path, char *const argv[]); • path is the absolute or relative path name of the command • argv is an array of pointers to null-terminated strings that represent the arguments to the command • argv[0] should be the name of the command • arg[n] must be NULL • execvp library function • int execvp(const char *file, char *const argv[]); • file is the absolute or relative path name of the command • PATH will be searched if the first character is not a /

  40. execl() example • #include <stdio.h>#include <unistd.h>main(){        printf("I'm process %i and I'm about to exec an ls -l\n", getpid());        execl("/bin/ls", "ls", "-l", NULL); /* Execute ls */        printf("This line should never be executed.\n");} > ./execl_ex I am process 7168 and I am about to exec an ls -l total 44 -rw-r--r-- 1 fatalay sjufacul 506 Feb 16 23:12 chdir_ex.c -rwxr-xr-x 1 fatalay sjufacul 6492 Feb 16 23:48 execl_ex -rw-r--r-- 1 fatalay sjufacul 183 Feb 16 23:48 execl_ex.c -rw-r--r-- 1 fatalay sjufacul 563 Feb 10 00:11 fork_ex1.c

  41. execvp example • See execvp_ex.c • #include <stdio.h>#include <unistd.h>main(int argc, char* argv[]){        fprintf(stdout, "Parent is about to fork child\n");        if (fork() == 0) /* child */        {                fprintf(stdout, "Child process is about to exec\n");                execvp(argv[1], &argv[1]); /* execute other program */                fprintf(stderr, "This line should never print\n");                fprintf(stderr, "Could not execute %s\n", argv[1]);        }        fprintf(stdout, "Parent is about to terminate\n");}

  42. Output argv[1] > ./execvp_ex ls -l Parent is about to fork child Parent is about to terminate Child process is about to exec > total 62 -rw-r--r-- 1 fatalay sjufacul 506 Feb 16 23:12 chdir_ex.c -rw-r--r-- 1 fatalay sjufacul 935 Feb 10 00:12 errno_ex.c -rwxr-xr-x 1 fatalay sjufacul 6572 Feb 16 23:52 execl_ex -rw-r--r-- 1 fatalay sjufacul 247 Feb 16 23:52 execl_ex.c -rwxr-xr-x 1 fatalay sjufacul 7136 Feb 17 15:22 execvp_ex -rw-r--r-- 1 fatalay sjufacul 1150 Feb 17 15:22 execvp_ex.c -rw-r--r-- 1 fatalay sjufacul 563 Feb 10 00:11 fork_ex1.c

  43. Process Termination Process executes last statement and then asks the operating system to delete it using the exit() system call. void exit(int status) //include <stdlib.h> Returns status data from child to parent 0: success, nonzero: failure If parent is executing a wait(), it is notified of child’s exit status is made available to parent If the parent is not waiting, the child's status will be made available to it when the parent subsequently executes wait( ) Process’ resources are deallocated by operating system Exit flushes all output streams and closes all open streams File descriptors are closed A SIGCHLD is sent to the parent process The PPID of all of its child processes is set to 1 (init)

  44. 0 0 exitcode 0 byte 3 byte 2 byte 1 byte 0 Status • It is stored as an integer • Assuming a 32-bit integer: • The high-order 16 bits are zero • Normal termination • Byte 1 contains the exit code (0 - 255) • Byte 0 contains zeros • Termination because of an un-caught signal • Byte 1 contains zeros • Byte 0 contains the signal number

  45. wait() • The wait( ) system call • pid_t wait(int *status); • Include: • #include <sys/types.h> • #include <sys/wait.h> • This call will suspend the parent process until any of its child processes terminates • Then the wait call returns and the parent process can continue • The return value from wait • Child is present - the terminating child's PID • No child present - -1 • If a process has one or more zombie children, wait returns immediately with the status of one of the zombies • status is a pointer to a location that will receive the child's exit status information

  46. wait_ex.c • /* This program demonstrates the wait system call   and the status returned by the child process*/#include <stdio.h>#include <stdlib.h>main(){        int pid, status, childPid;        printf("I'm the parent process and my PID is %i\n", getpid());        pid = fork();        if (pid != 0) /* parent */        {                printf("I'm the parent process with PID %i and PPID %i\n“, getpid(), getppid());                childPid = wait (&status); /* wait for child to terminate */                printf("A child with PID %i terminated with exit code %i\n“, childPid, status >> 8);                printf(" Parent - PID %i terminates\n", getpid());        }        else        {                printf("I'm the child process with PID %i and PPID %i\n“, getpid(), getppid());                printf(" Child - PID %i terminates\n", getpid());                exit( 15 );        }}

  47. Output I'm the parent process and my PID is 22580 I'm the parent process with PID 22580 and PPID 22553 I'm the child process with PID 22581 and PPID 22580 Child - PID 22581 terminates A child with PID 22581 terminated with exit code 15 Parent - PID 22580 terminates

  48. Process Creation (Cont.) UNIX examples fork()system call creates new process exec() system call used after a fork() to replace the process’ memory space with a new program

  49. waitpid() • waitpid( ) system call • pid_t waitpid(pid_t pid, int *status, int options); • pid specifies what to wait for • pid < -1 • Wait for a child whose GID is equal to the absolute value of pid • pid = -1 • Wait for any child to finish - same behavior as wait( ) • pid = 0 • Wait for a child whose GID is the same as the calling process • pid > 0 • Wait for child whose PID equals pid • status is the same as for wait( ) • options allows you to specify that a call to waitpid( ) should not suspend the parent process if no child process is ready to report its exit status

  50. Example • See waitpid_ex.c • Output > ./waitpid_ex I'm the parent process and my PID is 22664 I'm the parent process with PID 22664 and PPID 22553 I'm the first child process with PID 22665 and PPID 22664 I'm the second child process with PID 22666 and PPID 22664 Child2 - PID 22666 terminates Child1 - PID 22665 terminates A child with PID 22665 terminated with exit code 15 Parent - PID 22664 terminates

More Related