Chapter 2 Programs, Processes, and Threads Source: Robbins and Robbins, UNIX Systems Programming, Prentice Hall, 2003.

Slides:



Advertisements
Similar presentations
3.1 Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition Process An operating system executes a variety of programs: Batch system.
Advertisements

Part IV: Memory Management
More on Processes Chapter 3. Process image _the physical representation of a process in the OS _an address space consisting of code, data and stack segments.
Chapter 7 Process Environment Chien-Chung Shen CIS, UD
The Environment of a UNIX Process. Introduction How is main() called? How are arguments passed? Memory layout? Memory allocation? Environment variables.
Introduction to C Programming
Introduction to C Programming
Chapter 10.
The Process Model.
UNIX Process Control Bach 7 Operating Systems Course Hebrew University Spring 2007.
CS 311 – Lecture 14 Outline Process management system calls Introduction System calls  fork()  getpid()  getppid()  wait()  exit() Orphan process.
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
Advanced OS Chapter 3p2 Sections 3.4 / 3.5. Interrupts These enable software to respond to signals from hardware. The set of instructions to be executed.
C Programs Preprocessor commands –#ifdef –#include –#define Type and macro definitions Variable and function declarations Exactly one main function Function.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Unix Process Environment. main Function A C program starts execution with a function called main. The prototype for the main function is: int main (int.
Concurrency Sharing of resources in the same time frame Apparent concurrency is sharing the same CPU, memory, or I/O device Real concurrency is sharing.
Silberschatz, Galvin and Gagne ©2009 Operating System Concepts – 8 th Edition, Chapter 3: Processes.
Introduction to C Programming
Process. Process Concept Process – a program in execution Textbook uses the terms job and process almost interchangeably A process includes: – program.
Chapter 4: Threads Adapted to COP4610 by Robert van Engelen.
OBJECT MODULE FORMATS. The object module format we have employed as an educational device is called OMF (relocatable object format). It’s one of the earliest.
Chapter 4: Threads. 4.2CSCI 380 Operating Systems Chapter 4: Threads Overview Multithreading Models Threading Issues Pthreads Windows XP Threads Linux.
Chapter 4: Threads. 4.2 Silberschatz, Galvin and Gagne ©2005 Operating System Concepts Threads A thread (or lightweight process) is a basic unit of CPU.
1 Homework Introduction to HW7 –Complexity similar to HW6 –Don’t wait until last minute to start on it File Access will be needed in HW8.
Introduction to Processes CS Intoduction to Operating Systems.
C++ for Engineers and Scientists Second Edition Chapter 6 Modularity Using Functions.
Programming With C.
10/16/ Realizing Concurrency using the thread model B. Ramamurthy.
Recitation 9: Error Handling, I/O, Man Andrew Faulring Section A 4 November 2002.
CS 590 Programming Environments with UNIX. Computer Lab Account Course Homepage
Hardware process When the computer is powered up, it begins to execute fetch-execute cycle for the program that is stored in memory at the boot strap entry.
Chapter 6 UNIX Special Files Source: Robbins and Robbins, UNIX Systems Programming, Prentice Hall, 2003.
ITEC 502 컴퓨터 시스템 및 실습 Chapter 2-1: Process Mi-Jung Choi DPNM Lab. Dept. of CSE, POSTECH.
File IO and command line input CSE 2451 Rong Shi.
1 Threads Chapter 11 from the book: Inter-process Communications in Linux: The Nooks & Crannies by John Shapley Gray Publisher: Prentice Hall Pub Date:
Source: Operating System Concepts by Silberschatz, Galvin and Gagne.
Algorithms  Problem: Write pseudocode for a program that keeps asking the user to input integers until the user enters zero, and then determines and outputs.
System calls for Process management
CPS4200 Unix Systems Programming Chapter 2. Programs, Processes and Threads A program is a prepared sequence of instructions to accomplish a defined task.
Linux Processes Travis Willey Jeff Mihalik. What is a process? A process is a program in execution A process includes: –program counter –stack –data section.
Copyright ©: Nahrstedt, Angrave, Abdelzaher1 Processes and Threads.
Operating Systems Process Creation
CS4315A. Berrached:CMS:UHD1 Process Management Chapter 6.
1 CS503: Operating Systems Spring 2014 Part 0: Program Structure Dongyan Xu Department of Computer Science Purdue University.
12/22/ Thread Model for Realizing Concurrency B. Ramamurthy.
System calls for Process management Process creation, termination, waiting.
Chapter 11  Getting ready to program  Hardware Model  Software Model  Programming Languages  Facts about C++  Program Development Process  The Hello-world.
 2003 Prentice Hall, Inc. All rights reserved Basics of a Typical C++ Environment C++ systems –Program-development environment –Language –C++
Chapter 7 Process Environment Chien-Chung Shen CIS/UD
Error handling I/O Man pages
Exceptional Control Flow
Protection of System Resources
Linux Processes & Threads
Using Processes.
Tarek Abdelzaher Vikram Adve Marco Caccamo
Exceptional Control Flow: System Calls, Page Faults etc.
Threads and Cooperation
C++ for Engineers and Scientists Second Edition
Structure of Processes
System Structure and Process Model
Operating System Concepts
The Environment of Unix Process
Programs written in C and C++ can run on many different computers
Programming with Shared Memory
Tutorial 4.
Process Description and Control in Unix
EECE.4810/EECE.5730 Operating Systems
Process Description and Control in Unix
Presentation transcript:

Chapter 2 Programs, Processes, and Threads Source: Robbins and Robbins, UNIX Systems Programming, Prentice Hall, 2003.

2 POSIX Standard POSIX: Portable Operating System Interface (pronounced pahz-icks) Standardized the AT&T System V and the BSD flavors of UNIX Consists of a joint document first started in 1988 and finally approved in 2001 by both IEEE and the Open Group –The standardization effort was hurried up in 1998 by the threat of world domination of computer operating systems by Microsoft Windows ISO/IEC* approved POSIX in 2002 The standard is referred to as –The Single UNIX Specification, Version 3 (or) –IEEE Std , POSIX The POSIX standard also incorporates the international standard for ISO/ANSI C A POSIX-compliant implementation must support the POSIX base standard –Examples: Solaris 9, Redhat Linux 8, and MAC OS 10.2 * ISO/IEC : International Standards Organization / International Electrotechnical Commission

2.1 From Program to Process

4 From Program to Process Program – A prepared sequence of instructions to accomplish a defined task –A text editor is used to enter the human readable version of a program into a source code file –A compiler is used to convert the source code into a computer readable version that is stored in an object code file –A linker is used to combine the functions stored in one or more object code files or libraries into a single executable file –A loader is used to copy the contents of an executable file into a program image in main memory Process – An instance of a program that is running (or scheduled to run) in a computer Thread – A specific flow of control in a process –It represents a thread of execution within a process –Each thread has its own execution stack program counter register set process state (if using kernel threads)

2.3 Layout of a Program Image

6 Program Image in RAM

7 Portable Executable (PE) File Format DOS Header (64 bytes) MS-DOS Stub (57 bytes) PE Signature (4 bytes) File Header (20 bytes) Optional Header (224 bytes) Section Table Symbol Table String Table.text Section.data Section.rdata Section.idata Section (Import Table).edata Section (Export Table) 0 n

8 helloworld.exe (Cygwin) (1 of 2) ADDRESS DESCRIPTION DOS Header [64 bytes] MS-DOS Stub [57 bytes] (Contents not known) [7 bytes] PE Signature [4 bytes] File Header [20 bytes] Optional Header [224 bytes] Section Table [200 bytes] (** Zero-filled region **) [448 bytes] text section [ bytes] (Source: J. J. Tevis, findssv Presentation, August 2005)

9 helloworld.exe (Cygwin) (2 of 2) ADDRESS DESCRIPTION data section [4608 bytes] rdata section [35840 bytes] idata section [1183 bytes] More of Import Table (.idata section) [241 bytes] (** Zero-filled region **) [112 bytes] (Source: J. J. Tevis, findssv Presentation, August 2005)

10 pdf995s.exe (1 of 2) ADDRESS DESCRIPTION DOS Header [64 bytes] MS-DOS Stub [57 bytes] (Contents not known) [79 bytes] PE Signature [4 bytes] File Header [20 bytes] Optional Header [224 bytes] Section Table [200 bytes] (** Zero-filled region **) [376 bytes] text section [22016 bytes] (Source: J. J. Tevis, findssv Presentation, August 2005)

11 pdf995s.exe (2 of 2) ADDRESS DESCRIPTION rdata section [3072 bytes] (No additional details) [492 bytes] Import Table (.idata section) [2303 bytes] (No additional details) [181 bytes] Export Table (.edata section) [50 bytes] (No additional details) [46 bytes] data section [3584 bytes] rsrc section [1536 bytes] _winzip_ section [ bytes] (Source: J. J. Tevis, findssv Presentation, August 2005)

2.5 Function Return Values

13 Function Return Values Traditional UNIX functions usually return –1 (or sometimes NULL ) to indicate that an error has occurred –They also set the global variable errno to a value that indicates the specific error –A program should always check the return value of a function New POSIX functions do not use errno ; instead, the function returns the error number directly The perror() function outputs to standard error a message corresponding to the current value of errno –void perror(const char *s); // #include –If the value of s is not NULL, perror outputs the character string pointed to by s and follows it with a colon, a space, an error message, and a newline character The strerror() function returns a pointer to the system error message corresponding to the error code passed to it –char *strerror(int errorNumber); // #include –If successful, strerror() returns a pointer to the error string; no values are reserved for failure

14 Example Use of perror() int fileDescriptor; int status; // Robbins approach if (close(fileDescriptor) == -1) perror("Failed to close the file"); // Preferred approach status = close(fileDescriptor); if (status == -1) perror("Failed to close the file"); int close(int fildes); #include Preprocessor DirectivesFunction Prototype Source Code Example Failed to close the file: Invalid file descriptor Program Output

15 Example Use of strerror() int fileDescriptor; int status; status = close(fileDescriptor); if (status == -1) fprintf(stderr, "Error message: %s", strerror(errno)); int close(int fildes); #include Preprocessor DirectivesFunction Prototype Source Code Example Error message: Invalid file descriptor Program Output

2.10 Process Environment

17 Process Environment Environment list: an array of pointers to character strings of the form "name=value" –name specifies a specific environment variable –value specifies a character string value associated with the environment variable –The last entry of the array is NULL The external variable environ points to the process environment list when a process begins executing –extern char **environ; The getenv() function determines whether a specific variable has a value in the process environment –char *getenv(const char *name); // #include –If the variable has a value, getenv() returns a pointer to the character string containing the value; otherwise, it returns NULL –Example use: char *pathPtr; pathPtr = (char *) getenv("PATH"); if (pathPtr == NULL) printf("No path environment variable was found\n"); else printf("Contents of Path: %s\n", pathPtr);

18 Example Use of environ #include extern char **environ; int main(void) { int i; for (i = 0; environ[i] != NULL; i++) printf("%s\n", environ[i]); return 0; } // End main

19 Example contents of environ array USER=jjt107 LOGNAME=jjt107 HOME=/home/jjt107 PATH=/opt/local/bin:/usr/openwin/bin:/usr/bin:/opt/local/prog/bin:. SHELL=/bin/csh TZ=US/Central SSH_CLIENT= SSH_TTY=/dev/pts/4 TERM=vt100 SSH_AUTH_SOCK=/tmp/ssh-KeY22175/agent PWD=/home/jjt107/Files/CS410 OPENWINHOME=/usr/openwin MANPATH=/usr/man:/opt/local/man:/opt/local/common/man EDITOR=/usr/ucb/vi MOST_HELP=/opt/local/common/lib/most.doc XAPPLRESDIR=/opt/local/common/lib/app-defaults:/usr/openwin/lib/app-defaults LD_LIBRARY_PATH=/usr/local/netlib/lib LPDEST= LM_LICENSE_FILE=/opt/SUNWspro/license_dir/sunpro.lic,sp A_TERMCAP=/usr/local/uxb1/lib/acucobol-85/a_termcap A_CONFIG=/usr/local/uxb1/lib/acucobol-85/cblconfig

20 Example Use of getenv() int main(void) { char *variablePtr; variablePtr = (char *) getenv("PATH"); if (variablePtr == NULL) printf("No path environment variable was found\n"); else printf("Contents of Path: %s\n", variablePtr); return 0; } // End main

2.11 Terminating a Process

22 Process Termination When a process terminates, timers and signals are canceled, virtual memory resources are released, and opened files are closed The operating system then notifies the parent of the process in response to a wait() function call In UNIX, a process does not completely release its resources after termination until the parent waits for it –If its parent is not waiting when the process terminates, the process becomes a zombie –In UNIX, the init process adopts orphaned processes and periodically waits for children processes so that they will terminate normally Normal termination occurs under the following conditions –Explicit return from the main function –Implicit return from the main function (the function ends) –Explicit call to the exit() function

23 The exit() and atexit() Functions void exit(int status); // #include int atexit(void (*func)(void)); The exit() function calls user-defined exit handlers that were registered by the atexit() function in the reverse order of registration After calling the user-defined handlers, the exit() function flushes any open streams that have unwritten buffered data, closes all open streams, and terminates process control Using the return statement from the main function has the same effect as calling the exit() function with the corresponding status value –An implicit end of the main function has the same effect as calling exit(0) The atexit() function installs a user-defined exit handler and takes a single parameter: the name of the function to be executed as a handler Multiple calls to atexit() are used to install more exit handlers If successful, atexit() returns 0; otherwise, it returns a nonzero value

24 Example use of exit() and atexit() functions #include // Function prototypes void showDateAndTime(void); // ************************************************************* int main(void) { int answer; int value; int status; status = atexit(showDateAndTime); if (status != 0) { fprintf(stderr, "Error: Failed to install exit handler\n"); exit(1); } // End if srand(time(NULL)); // Set seed value for random number generator if ((rand() % 3) == 0) // Results in true condition about 1/3 of the time { answer = value / 0; // Causes a runtime abort to occur } // End if else fprintf(stderr, "Normal process termination\n"); return 0; } // End main (More on next slide)

25 Example exit handler // ********************************************************* void showDateAndTime(void) { time_t currentTime; currentTime = time(NULL); printf("Current date and time: %s\n", ctime(&currentTime)); } // End showDateAndTime

26 Example Program Run uxb3% a.out Arithmetic Exception uxb3% a.out Normal process termination Current date and time: Tue Feb 20 11:32: uxb3% a.out Arithmetic Exception