CPS4200 Unix Systems Programming Chapter 2. Programs, Processes and Threads A program is a prepared sequence of instructions to accomplish a defined task.

Slides:



Advertisements
Similar presentations
Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Advertisements

Introduction to C Programming
Copyright © 2000, Daniel W. Lewis. All Rights Reserved. CHAPTER 10 SHARED MEMORY.
Programming Languages and Paradigms The C Programming Language.
1 Chapter 10 Strings and Pointers. 2 Introduction  String Constant  Example: printf(“Hello”); “Hello” : a string constant oA string constant is a series.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
CPS3340 COMPUTER ARCHITECTURE Fall Semester, /17/2013 Lecture 12: Procedures Instructor: Ashraf Yaseen DEPARTMENT OF MATH & COMPUTER SCIENCE CENTRAL.
Chapter 7 Process Environment Chien-Chung Shen CIS, UD
Chapter 7: User-Defined Functions II
The Environment of a UNIX Process. Introduction How is main() called? How are arguments passed? Memory layout? Memory allocation? Environment variables.
 Scope and linkage  Storage classes  Automatic memory  Dynamic memory  Memory Model.
Memory Image of Running Programs Executable file on disk, running program in memory, activation record, C-style and Pascal-style parameter passing.
1 1 Lecture 4 Structure – Array, Records and Alignment Memory- How to allocate memory to speed up operation Structure – Array, Records and Alignment Memory-
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
Functions Definition: Instruction block called by name Good design: Each function should perform one task and do it well Functions are the basic building.
Run time vs. Compile time
C Programs Preprocessor commands –#ifdef –#include –#define Type and macro definitions Variable and function declarations Exactly one main function Function.
1 Functions and Structured Programming. 2 Structured Programming Structured programming is a problem-solving strategy and a programming methodology. –The.
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.
1 Run time vs. Compile time The compiler must generate code to handle issues that arise at run time Representation of various data types Procedure linkage.
C Lecture Notes Functions (Cont...). C Lecture Notes 5.8Calling Functions: Call by Value and Call by Reference Used when invoking functions Call by value.
Overview scope - determines when an identifier can be referenced in a program storage class - determines the period of time during which that identifier.
Command line arguments. – main can take two arguments conventionally called argc and argv. – Information regarding command line arguments are passed to.
University of Washington CSE 351 : The Hardware/Software Interface Section 5 Structs as parameters, buffer overflows, and lab 3.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Chapter 19 Data Structures Data Structures A data structure is a particular organization of data in memory. We want to group related items together.
System Calls 1.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
chap13 Chapter 13 Programming in the Large.
Variables, Functions & Parameter Passing CSci 588 Fall 2013 All material not from online sources copyright © Travis Desell, 2011.
Stack and Heap Memory Stack resident variables include:
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Processes and Threads CS550 Operating Systems. Processes and Threads These exist only at execution time They have fast state changes -> in memory and.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
18. DECLARATIONS.
Copyright © The McGraw-Hill Companies, Inc. Permission required for reproduction or display. C H A P T E R F I V E Memory Management.
User Defined Functions Chapter 7 2 Chapter Topics Void Functions Without Parameters Void Functions With Parameters Reference Parameters Value and Reference.
System calls for Process management
C Functions Three major differences between C and Java functions: –Functions are stand-alone entities, not part of objects they can be defined in a file.
RUN-Time Organization Compiler phase— Before writing a code generator, we must decide how to marshal the resources of the target machine (instructions,
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
Dale Roberts CSCI 230 Functions Scope, Parameter Passing, Storage Specifiers Department of Computer and Information Science, School of Science, IUPUI Dale.
CS4315A. Berrached:CMS:UHD1 Process Management Chapter 6.
Slides created by: Professor Ian G. Harris Hello World #include main() { printf(“Hello, world.\n”); }  #include is a compiler directive to include (concatenate)
12/22/ Thread Model for Realizing Concurrency B. Ramamurthy.
Process Management Azzam Mourad COEN 346.
1 Becoming More Effective with C++ … Day Two Stanley B. Lippman
1 MORE ON MODULAR DESIGN: MODULE COMMUNICATIONS. 2 WHEN A FUNCTION IS INVOKED, MEMORY IS ALLOCATED LOCALLY FOR THE FORMAL PARAMETERS AND THE VALUE OF.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Chapter 12: Programming in the Large By: Suraya Alias 1-1.
+ Storage Classes and Linkage. + Introduction Scope describe the region or regions of a program that can access and identifier Variables can be shared.
Today’s Material Strings Definition Representation Initialization
1 Chapter 15-1 Pointers, Dynamic Data, and Reference Types Dale/Weems.
Multi-dimensional Arrays and other Array Oddities Rudra Dutta CSC Spring 2007, Section 001.
MORE POINTERS Plus: Memory Allocation Heap versus Stack.
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
Chapter 7 Process Environment Chien-Chung Shen CIS/UD
Stack and Heap Memory Stack resident variables include:
The Machine Model Memory
ENERGY 211 / CME 211 Lecture 25 November 17, 2008.
C Basics.
Programmazione I a.a. 2017/2018.
Instructor: Ioannis A. Vetsikas
Chapter 14 - Advanced C Topics
Memory Allocation CS 217.
Object Oriented Programming in java
CSE 451: Operating Systems Autumn 2004 Module 4 Processes
SPL – PS2 C++ Memory Handling.
Presentation transcript:

CPS4200 Unix Systems Programming Chapter 2

Programs, Processes and Threads A program is a prepared sequence of instructions to accomplish a defined task. –.c and.h files –Variables and functions declarations, type and macro definitions (typedef), preprocessor commands (#ifdef, #include, #define) A compiler translates the instructions to produce an executable module. When the program is run, the executable module becomes a program image in main memory. A process is an instance of a program that is executing.

Programs, Processes and Threads A process has an address space/execution state and starts with a single flow of control. –The process must have an ID (PID). The flow of control executes a sequence of instructions called a thread of execution. A thread of execution is a logically related sequence of instruction addresses assigned to the program counter during the execution of a program's code.

Programs, Processes and Threads Context switch: The point at which execution switches from one process to another. Example 2.2 –Process 1 executed statements 245, 246 and 247 in a loop and process 2 executes the statements 10, 11, 12, 13,.... –If the CPU starts executing process 1, loses the CPU after 5 instructions, and then executes 4 instructions of process 2 before losing the CPU, the instructions executed might be: –245 1, 246 1, 247 1, 245 1, 246 1, 10 2, 11 2, 12 2, 13 2, 247 1, 245 1, 246 1,...

Programs, Processes and Threads –There are two threads of execution: –245 1, 246 1, 247 1, 245 1, 246 1, and 10 2, 11 2, 12 2, –The subscript indicates which process is executing and appears only for clarity. A thread is an abstract data type that represents a thread of execution of a process.

Programs, Processes and Threads Thread has its own execution stack, program counter value, and state. A programmer can achieve parallelism with low overhead but may require synchronization. Process  heavyweight Thread  lightweight process

Programs, Processes and Threads A thread has: –A thread ID –A program counter –A register set –A stack

Layout of Programs Image in Main Memory

Activation record: –A block of memory allocated on the top of the process stack to hold the execution context of a function during a call. –It contains return address, the parameter, status information and a copy of some of the CPU register values at the time of the call. Storage allocated on the heap persists until it is freed or until the program exits.

Layout of Programs Image in Main Memory Activation record: –A block of memory allocated on the top of the process stack to hold the execution context of a function during a call. –It contains return address, the parameter, status information and a copy of some of the CUP register values at the time of the call. Storage allocated on the heap persists until it is freed or until the program exits.

Layout of Programs Image in Main Memory Static variables that are not explicitly initialized in their declaration are initialized to 0 at run time. Initialized static variables  part of the executable module Un-initialized static variables  not part of the executable module Examples

Argument Arrays An argument array is an array of pointers terminated by a NULL pointer. Each element of the array is of type char * and represents a string. For example: The argv array for the call mine -c

Argument Arrays

The shell must do this when you execute a command. argv[] is an array of pointers to chars In C, this is the same as a pointer to a pointer to a char. (double pointers)

Create an Argument Array with makeargv Makeargv creates an argument array from a string of tokens. Method 1: One way to write a function to do this is: char **makeargv(char *s) it returns a pointer to an argv array or returns a NULL pointer if the call fails

Create an Argument Array with makeargv Method 2: If you want to return the number of tokens, you can pass a pointer to the arg array as in: int makeargv(char *s, char ***argvp)

Create an Argument Array with makeargv Method 3: The version we will use has an additional parameter that specifies a string of delimiters: int makeargv(const char *s, const char *delimiters, char ***argvp) The const for the first two parameters indicates that the strings should not be modified by the function. Note: C language is call-by-value Const means that the function does not modify the memory pointed to by the first two parameters

Create an Argument Array with makeargv Example: argtest “This is a test”

#include int makeargv(const char *s, const char *delimiters, char ***argvp); int main(int argc, char *argv[]) { char delim[] = " \t"; int i; char **myargv; int numtokens; if (argc != 2) { fprintf(stderr, "Usage: %s string\n", argv[0]); return 1; } if ((numtokens = makeargv(argv[1], delim, &myargv)) == -1) { fprintf(stderr, "Failed to construct an argument array for %s\n", argv[1]); return 1; } printf("The argument array contains:\n"); for (i = 0; i < numtokens; i++) printf("%d:%s\n", i, myargv[i]); return 0; } testarg.c

How to write makeargv Can use strtok: #include char *strtok(char *restrict s1, const char *restrict s2); s1 is the string to parse s2 is a string of delimiters restrict qualifier on the two paramters requires that any object referenced by s1 can not also be accessed by s2 returns a pointer to the next token or NULL if none left. –First call: s1 points to the string to parse –Additional calls: s1 is NULL. –Note: the string s1 is modified.

How to write makeargv We do not want the string passed to makeargv to be modified so we allocate space for another copy of the string. –Make a pass with strtok to count the tokens. –Use the count to allocate the argv array –Make a second pass with strtok to set the pointers in the argv array.

How to write makeargv Use malloc to allocate a buffer t for parsing the string in place. Copy s to t. Make a pass through the string t, using strtok to conunt the tokens. Use the count( numtokens ) to allocate an argv array Copy s into t again Use strtok to obtain pointers to the individual tokens, modifying t and effectively parsing t in place.

How to write makeargv Strspn(char * s1, char * s2) The strspn() function returns the length of the initial segment of string s1 that consists entirely of characters from string s2.

The makeargv makes a working copy of the string s so that it does not modify that input parameter.

The use of strtok to allocate strings in place for makeargv.

Thread Safe Functions strtok is not safe to use with threads since it remembers the previous state. See program: wordaveragebad.c Another version is available: strtok_r in which you pass another parameter which is used to remember where it is. #include char *strtok_r(char *restrict s1, const char *restrict s2, char **restrict lasts); You must declare a char pointer to hold the current position and pass a pointer to it as the last argument to strtok_r.

Storage and Linkage Classes Storage classes: static and automatic –static storage class refers to variables that, once allocated, persist throughout the execution of a program. –automatic storage class refers to variables which come into existence when the block in which they are declared is entered and are discarded when the defining block is exited. –Variables declared inside a function have automatic storage class unless they are declared to be static. These are usually allocated on the program stack. –Variables defined outside any functions have static storage class.

Storage and Linkage Classes The word static has two meanings is C. One is related to storage class and the other to linkage class..

Storage and Linkage Classes Linkage classes Linkage class determines whether variables can be accessed in files other than the one in which they are declared. –Internal linkage class means they can only be accessed in the file in which they are declared. –External linkage class means they can be accessed in other files. –variables declared outside any function and function name identifiers have external linkage by default. They can be given internal linkage with the key word static. –Variables declared inside a function are only known inside that function and are said to have no linkage.