Download presentation
Presentation is loading. Please wait.
1
Chapter 2: part I Processes
2
Outline Process Concept Process Control Block Context Switch
System call Process Concept Process Control Block Context Switch OS Scheduler Operations on Processes System calls related to process
3
System Calls Programming interface to services provided by OS
Typically written in a high-level language (C or C++) Mostly accessed by programs via a high-level Application Program Interface (API) rather than direct system call use Three most common APIs Win32 API for Windows POSIX API for POSIX-based systems (including all versions of UNIX, Linux, and Mac OS X) => PORTABILITY Your mycp.cpp program can be compiled and run on a lot of different systems In manual page of read, write, …, “CONFORMING TO” section (SVr4, 4.3 BSD, POSIX ) If target system supports these API standard, your program will work… Java API for Java virtual machine (JVM)
4
Example of Standard API
Consider the ReadFile() function in the Win32 API—a function for reading from a file A description of the parameters passed to ReadFile() HANDLE file—the file to be read LPVOID buffer—a buffer where the data will be read into and written from DWORD bytesToRead—the number of bytes to be read into the buffer LPDWORD bytesRead—the number of bytes read during the last read LPOVERLAPPED ovl—indicates if overlapped I/O is being used
5
Example of System Calls
System call sequence to copy the contents of one file to another file Recall: strace command?
6
System Call Implementation
a number associated with each system call, e.g., open => 3 write => 4, … System call interface invokes intended system call in OS kernel and returns status of the system call and any return values Caller need know nothing about how system call is implemented Just needs to obey API and understand what OS will do as a result Most details of OS interface hidden from programmer by API Managed by run-time support library (set of functions built into libraries included with compiler) * a table indexed according to system call numbers * stores pointers to corresponding routines that implement system call
7
Standard C Library Example
C++: cin>>, cout << operation calls read, write C program invoking printf() library call, which calls write() system call From $man man 1 Executable programs or shell commands 2 System calls (functions provided by the kernel) 3 Library calls (functions within program libraries) 4 Special files (usually found in /dev) 5 File formats and conventions eg /etc/passwd …
8
System Programs System programs provide a convenient environment for program development and execution. The can be divided into: File manipulation Status information File modification Programming language support Program loading and execution Communications Application programs Most users’ view of the operation system is defined by system programs, not the actual system calls System programs are really nothing but system provided user programs Use OS services by making system call Any user can write their own commands such as cp, mkdir, ps, bash, …
9
What is bash? It’s a program/command/executable file in the disk
$which bash /usr/bin/bash $ file /bin/bash /bin/bash: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux , BuildID[sha1]=def017565ddde4dd416c53c433a5a2ee6ac22f08, stripped One kind of command line interpreters: interprets and executes command line Bourne shell (sh) ash,dash Bash (Bourne Again shell) Csh, tcsh Ksh Zsh Every user can choose what shell to use: Unix command: chsh allow you to change your shell
10
Bash: interactive mode
interprets and executes command line that user types (in interactive mode) in the keyboard: Pseudocode of bash (or any shell program): while (1) { read a line from standard input parse the line into words (first word is cmd, others are arguments) if cmd==“exit”, exit the program create a new process to run the program passing arguments to it wait for the process to finish/exit }
11
Bash Scripting Mode To automate things that you will be repeatedly doing, put commonly used sequence of command lines into a text file, e.g., test_mycp.sh e.g., $bash test_mycp.sh Updated pseudo-code of shell if (argc>1) src_fd = open script file (argv[1]) else src_fd = 0 // the standard input while (1) { read next line from src_fd parse the line into words (first word is cmd, others are arguments) if (cmd==“exit”) _exit (0); // create a new child process to run the program passing arguments to it wait for the child process to finish/exit }
12
Bash Script To automate things that you will be repeatedly doing, put commonly used sequence of command lines into a text file, e.g., test_mycp.sh e.g., $bash test_mycp.sh Bash script: a text file which will be interpreted and executed by bash E.g., ~zhang/bin/config3595, or submit3595 Why you can execute such text file? First line of the file: #!/bin/bash tells what program should be used to interpret it … $testmycp.sh Same as $bash testmycp.sh If you put #!/…/mycp in first line, your mycp program will be called ! Similarly for python, perl, awk, sed, … commands, all are a kind of scripting langauge.
13
Outline Process Concept Process Control Block Context Switch
System call Process Concept Process Control Block Context Switch OS Scheduler Operations on Processes System calls related to process
14
Multiprogramming and Process
(a) Multiprogramming of four programs. (b) Conceptual model of four independent, sequential processes. (c) Only one program is active at once. Tanenbaum, Modern Operating Systems 3 e, (c) 2008 Prentice-Hall, Inc. All rights reserved
15
Process Concept Process – a program in execution A process includes:
program counter (PC) value: keep address of next instruction other registers value Address space (core image): the range of memory space for the process program (code) that the process is running variables value: global, dynamic records of active function calls (ongoing calls) Opened files, I/O devices …
16
A process’s Address Space
In class demo: hand-trace a program’s execution
17
Some fields of a typical process control table entry.
Process Control Block Some fields of a typical process control table entry. Tanenbaum, Modern Operating Systems 3 e, (c) 2008 Prentice-Hall, Inc. All rights reserved
18
Process Creation Events which cause process creation:
System initialization. Execution of a process creation system call by a running process. A user request to create a new process. Initiation of a batch job. Tanenbaum, Modern Operating Systems 3 e, (c) 2008 Prentice-Hall, Inc. All rights reserved
19
Process Termination Events which cause process termination:
Normal exit (voluntary). Error exit (voluntary). Fatal error (involuntary). Killed by another process (involuntary). Tanenbaum, Modern Operating Systems 3 e, (c) 2008 Prentice-Hall, Inc. All rights reserved
20
Process States Figure 2-2. A process can be in running, blocked, or ready state. Transitions between these states are as shown. Tanenbaum, Modern Operating Systems 3 e, (c) 2008 Prentice-Hall, Inc. All rights reserved
21
Implementation of Processes (1)
lowest layer of a process-structured operating system handles interrupts and scheduling. Above that layer are sequential processes. Tanenbaum, Modern Operating Systems 3 e, (c) 2008 Prentice-Hall, Inc. All rights reserved
22
CPU Switch From Process to Process
23
Context Switch 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 Context-switch time is overhead; system does no useful work while switching Time dependent on hardware support
24
Hardware Interrupt and Context Saving Details
Skeleton of what lowest level of OS does when an interrupt occurs. Tanenbaum, Modern Operating Systems 3 e, (c) 2008 Prentice-Hall, Inc. All rights reserved
25
Outline Process Concept Process Control Block Context Switch
System call Process Concept Process Control Block Context Switch OS Scheduler Operations on Processes POSIX System calls related to process
26
Unix: Process Creation
Parent process create children processes, which, in turn create other processes, forming a tree of processes Generally, process identified and managed via a process identifier (pid), an integer number Zombie process: undead process a child process that have finished execution, but its entry not deleted from Process Control Table (not dead), waiting for its parent to get its exit status Orphan Process: child without parent a child process whose original parent has terminated, and therefore adopted by process 1
27
Process Termination Process executes last statement and asks the operating system to delete it (exit) Output data from child to parent (via wait) Process’ resources are deallocated by operating system Parent may terminate execution of children processes (abort) Child has exceeded allocated resources Task assigned to child is no longer required If parent is exiting Some operating system do not allow child to continue if its parent terminates All children terminated - cascading termination
28
A tree of processes on a typical Solaris
29
Process Creation Address space UNIX examples Child duplicate of parent
Child has a program loaded into it 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 execl, execle, execlp, execv, execvp, execvP -- execute a file
30
System call: fork pid_t fork(void); creates a new process by duplicating calling process. The new process, referred to as the child, is an exact duplicate of the calling process, referred to as the parent, except for the following points: child has its own unique process ID, and this PID does not match ID of any existing process group child's parent process ID is the same as parent's process ID.
31
C Program Example int main() { pid_t pid; int a=1; pid = fork();
if (pid < 0) { /* error occurred */ fprintf(stderr, "Fork Failed"); exit(-1); } if (pid == 0) { /* child process */ printf ("Child process ...\n"); else { /* parent process */ printf ("Parent process...\n"); for (int i=0;i<20;i++) a++; cout <<pid << ": a=" << a << endl;
32
duplicate/separate address space
Child process address space Parent process address space Implication? behavior observed in demo program…
33
How many processes are created?
int main() { pid_t pid; for (int i=0; i<2; i++) pid = fork(); } Demo: fork_number.c
34
Parent & Child Process Child’s address space is a clone of that of the Parent Things not inherited: Process resource utilizations and CPU time counter (reset to zero in the child) The child's set of pending signals is initially empty semaphore adjustments, process-associated record locks from, timers from its parent, parent's memory locks, outstanding asynchronous I/O operations Things inherited/shared: parent's set of open file descriptors. int src_fd = open (argv[1], O_RDONLY); pid = fork(); Each file descriptor in the child refers to the same open file description as corresponding file descriptor in parent, i.e., they share open file status flags, current file offset, and signal- driven I/O attributes How does parent and child process communicate? Inter-Process Communication, pipes, shared memory, message passing, …
35
Parent & Child Process wait, waitpid, waitid - wait for process to change state pid_t wait(int *status); pid_t waitpid(pid_t pid, int *status, int options); int waitid(idtype_t idtype, id_t id, siginfo_t *infop, int options); to wait for state changes in a child of calling process, and obtain information about the child whose state has changed. child terminated; child was stopped by a signal; child was resumed by a signal. If a child has already changed state, then these calls return immediately. Otherwise, they block until either a child changes state or a signal handler interrupts the call…
36
C Program Example pid_t pid; int main() { /* fork another process */
pid = fork(); if (pid < 0) { /* error occurred */ fprintf(stderr, "Fork Failed"); exit(-1); } // now both parent and child process are running this… else if (pid == 0) { /* child process */ execlp("/bin/ls", "ls", NULL); else { /* I am parent! pid is PID of child process */ /* parent will wait for the child to complete */ wait (NULL); printf ("Child Complete"); exit(0);
37
Executing a Program execlp("/bin/ls", "ls", NULL); int execlp(const char *file, const char *arg, ...); First argument, const char *file, points to filename associated with file to be executed. const char *arg and subsequent ellipses can be thought of as arg0, arg1, ..., argn. Together they describe a list of one or more pointers to null-terminated strings that represent argument list available to executed program. available to problem as parameters to main int main (int argc, char * argv[]) list of arguments must be terminated by a null pointer, and, since these are variadic functions, this pointer must be cast (char *) NULL.
38
Related function calls
int execl(const char *path, const char *arg, ...); int execlp(const char *file, 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 execvpe(const char *file, char *const argv[], char *const envp[]); First argument: path: path (relative or absolute) to the program to be executed file: path or file name of the program to be executed, “ls”, “/home/zhang/bin/config3595” => the system call will search for the file if path not provided l/cv: List of arguments or array of arguments e: with or without environment variables
39
Environment variables
Environment variables are a set of dynamic named values that can affect the way running processes will behave on a computer. They are part of the environment in which a process runs. e.g., a running process can query value of TEMP environment variable to discover a suitable location to store temporary files, HOME or USERPROFILE variable to find directory structure owned by the user running the process. other examples: PWD, PATH You can defined your own: e.g., export SERVER=storm.cis.fordham.edu You can access environment variable in command line: $echo $PATH ## to view the value of PATH variable $ssh History: introduced in their modern form in 1979 with Version 7 Unix, … Now commonly used in all Unix variants and Windows.
40
System call: error message
Reporting Error Message: file does not exist, directory not writable, …. #include <errno.h> defines integer variable errno, set by system calls and some library functions in the event of an error to indicate what went wrong. if (errno== …. ) cout <<“ corresponding error message …”; else … perror - print a system error message void perror(const char *s); produces a message on standard error output, describing last error encountered during a call to a system or library function. First, string s is printed, followed by a colon and a blank, and then error message. if (src_fd = read (argv[1], O_RDONLY)<0) { perror (“Opening src file to read”; exit (1); }
41
getrlimit, setrlimit, prlimit - get/set resource limits
SYNOPSIS #include <sys/time.h> #include <sys/resource.h> int getrlimit(int resource, struct rlimit *rlim); int setrlimit(int resource, const struct rlimit *rlim); int prlimit(pid_t pid, int resource, const struct rlimit *new_limit, struct rlimit *old_limit); Feature Test Macro Requirements for glibc (see feature_test_macros(7)): prlimit(): _GNU_SOURCE && _FILE_OFFSET_BITS == 64 DESCRIPTION The getrlimit() and setrlimit() system calls get and set resource limits respectively. Each resource has an associated soft and hard limit, as defined by the rlimit structure: struct rlimit { rlim_t rlim_cur; /* Soft limit */ rlim_t rlim_max; /* Hard limit (ceiling for rlim_cur) */ };
42
Single and Multithreaded Processes
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.