Environment of UNIX Processes [Slides from Prof. Yangsae Moon]

Slides:



Advertisements
Similar presentations
Dynamic memory allocation
Advertisements

Dynamic Memory Allocation in C.  What is Memory What is Memory  Memory Allocation in C Memory Allocation in C  Difference b\w static memory allocation.
Carnegie Mellon 1 Dynamic Memory Allocation: Basic Concepts : Introduction to Computer Systems 17 th Lecture, Oct. 21, 2010 Instructors: Randy Bryant.
Chris Riesbeck, Fall 2007 Dynamic Memory Allocation Today Dynamic memory allocation – mechanisms & policies Memory bugs.
Linux/UNIX Programming APUE (The Environment of a UNIX Process) [Ch. 7] 최 미 정 강원대학교 컴퓨터과학전공.
Chapter 7 Process Environment Chien-Chung Shen CIS, UD
LINUX System Process (additional slides)
Growing Arrays in C By: Victoria Tielebein CS 265- Spring 2011.
Chapter 14 - Advanced C Topics Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Contents 1. Preface/Introduction 2. Standardization and Implementation 3. File I/O 4. Standard I/O Library 5. Files and Directories 6. System Data Files.
1 Memory Allocation Professor Jennifer Rexford COS 217.
User-Level Memory Management in Linux Programming
Agenda  Review: pointer & array  Relationship between pointer & array  Dynamic memory allocation.
More Pointers Write a program that: –Calls a function to input an integer value –The above function calls another function that will double the input value.
System Files and Process Environment Password file Group file System identification Time Process environment.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 14 - Advanced C Topics Outline 14.1Introduction.
[Unix Programming] Process Basic Young-Ju, Han
Pointer applications. Arrays and pointers Name of an array is a pointer constant to the first element whose value cannot be changed Address and name refer.
CP104 Introduction to Programming Structure II Lecture 32 __ 1 Data Type planet_t and Basic Operations Abstract Data Type (ADT) is a data type combined.
Memory and Files Dr. Andrew Wallace PhD BEng(hons) EurIng
Week 7 - Friday.  What did we talk about last time?  Allocating 2D arrays.
Memory allocation CSE 2451 Matt Boggus. sizeof The sizeof unary operator will return the number of bytes reserved for a variable or data type. Determine:
Introduction to C Programming in Unix Environment - II Abed Asi Extended System Programming Laboratory (ESPL) CS BGU Fall 2014/2015 Some slides.
The Environment of a UNIX Process. Introduction How is main() called? How are arguments passed? Memory layout? Memory allocation? Environment variables.
Process Control Hua LiSystems ProgrammingCS2690Process Control Page 1 of 41.
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-
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.
Advanced Programming in the UNIX Environment Hop Lee.
Command line arguments. – main can take two arguments conventionally called argc and argv. – Information regarding command line arguments are passed to.
System Calls 1.
Security Exploiting Overflows. Introduction r See the following link for more info: operating-systems-and-applications-in-
Class 2 CSI2172
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility,
1 Logging in to a UNIX System init ( Process ID 1 created by the kernel at bootstrap ) spawns getty for every terminal device invokes our login shell terminal.
1 Program Layout in memory –Code –Data Global variables –Stack Local variables & function Invocation Frames –Heap Dynamically allocated memory Today’s.
University of Washington Today Finished up virtual memory On to memory allocation Lab 3 grades up HW 4 up later today. Lab 5 out (this afternoon): time.
ECE 103 Engineering Programming Chapter 47 Dynamic Memory Alocation Herbert G. Mayer, PSU CS Status 6/4/2014 Initial content copied verbatim from ECE 103.
Chapter 2 Programs, Processes, and Threads Source: Robbins and Robbins, UNIX Systems Programming, Prentice Hall, 2003.
CPS4200 Unix Systems Programming Chapter 2. Programs, Processes and Threads A program is a prepared sequence of instructions to accomplish a defined task.
Linux/UNIX Programming APUE (Process Control) 문양세 강원대학교 IT 대학 컴퓨터과학전공.
제 11 장 프로세스 시스템 프로그래밍 1. Objectives Process Start and Exit Create a child process Execute a new program within a process Signal System boot 2.
1 CS503: Operating Systems Spring 2014 Part 0: Program Structure Dongyan Xu Department of Computer Science Purdue University.
+ Dynamic memory allocation. + Introduction We often face situations in programming where the data is dynamics in nature. Consider a list of customers.
CS415 C++ Programming Takamitsu Kawai x4212 G11 CERC building WV Virtual Environments Lab West Virginia University.
Arrays, Strings, and Memory. Command Line Arguments #include int main(int argc, char *argv[]) { int i; printf("Arg# Contents\n"); for (i = 0; i < argc;
Today’s Material Strings Definition Representation Initialization
1 System Programming Chapter 7. 2 Fun Stuff Touch-based Communication.
S -1 Processes. S -2 wait and waitpid (11.2) Recall from a previous slide: pid_t wait( int *status ) wait() can: (a) block; (b) return with status; (c)
“Success consists of going from failure to failure without loss of enthusiasm.” Winston Churchill.
Chapter 7 Process Environment Chien-Chung Shen CIS/UD
Linux/UNIX Programming APUE (Process Control) 문양세 강원대학교 IT 대학 컴퓨터과학전공.
Stack and Heap Memory Stack resident variables include:
LINUX System Process in Detail
Linux Processes & Threads
malloc(): Dynamic Memory Management
Using Processes.
CSCI206 - Computer Organization & Programming
Unix Process Course code: 10CS62 Prepared by : Department of CSE.
Chapter 14 - Advanced C Topics
CSC215 Lecture Memory Management.
Dynamic Memory Allocation
Memory Allocation CS 217.
The Environment of Unix Process
EENG212 – Algorithms & Data Structures Fall 07/08 – Lecture Notes # 5b
C Programming Lecture-8 Pointers and Memory Management
(PART 2) prepared by Senem Kumova Metin modified by İlker Korkmaz
Dynamic Memory – A Review
Presentation transcript:

Environment of UNIX Processes [Slides from Prof. Yangsae Moon]

Process 실행 2 Kernel exec system call C start-up routine user process int main(int argc, char * argv[]); call return

main() function int main(int argc, char *argv[]); argc : the number of command-line arguments argv[] : an array of pointers to the arguments C Start-Up Routine Started by the kernel (by the exec system call) Take the command-line arguments and the environment from the kernel 3

Process Termination Normal Termination Return from main() Calling exit() // with cleanup process Calling _exit() // without cleanup process Abnormal Termination Calling abort() Terminated by a signal 4

Page 5 exit() 프로세스를 정상적으로 종료한다. Cleanup Processing 을 수행한다. 모든 열려진 스트림 ( 파일 등 ) 을 닫고, 출력 버퍼의 내용을 디스크에 쓴다. status the exit status of a process ( 프로세스의 리턴 값으로 이해할 수 있음 ) 이 값은 UNIX shell 에 의해서 사용됨 (Shell Programming 에서 이용할 수 있음 ) #include void exit(int status);

Page 6 _exit() 프로세스를 정상적으로 종료한다. Kernel 로 즉시 리턴한다. (Cleanup Processing 을 수행하지 않는다.) #include void _exit(int status);

Page 7 atexit() exit handler 를 등록한다. 프로그램이 종료할 때 (exit() 이 호출되었을 때 ) 수행하는 함수들을 등록 프로세스당 32 개까지 등록 가능함 func An exit handler A function pointer exit() 은 exit handler 들을 등록된 역순으로 호출한다. #include void atexit(void (*func)(void)); returns: 0 if OK, nonzero on error

Page 8 C Program Start and Termination return call exit function user function main function C start-up routine exit handler standard I/O cleanup kernel user process exit (does not return) exit (does not return) exit (does not return) call return call return call return …… _exit exec _exit return call

Page 9 예제 : exit handlers (1/2) /* doatexit.c */ static void my_exit1(void), my_exit2(void); int main(void) { if (atexit(my_exit2) != 0) perror("can't register my_exit2"); if (atexit(my_exit1) != 0) perror("can't register my_exit1"); if (atexit(my_exit1) != 0) perror("can't register my_exit1"); printf("main is done\n"); return 0; } static void my_exit1(void) { printf("first exit handler\n"); } static void my_exit2(void) { printf("second exit handler\n"); }

Page 10 예제 : exit handlers (2/2) 실행 결과

Page 11 Command-Line Arguments exec() can pass command-line arguments to a new program. argc 에 Argument 개수를, argv 에 Argument 를 각각 전달한다. Part of normal operation of Unix Shells. argv[argc] is NULL.

Page 12 예제 : echoarg.c #include // echoarg.c int main(int argc, char *argv[]) { int i; for (i = 0; i < argc; i++) /* echo all command-line args */ printf("argv[%d]: %s\n", i, argv[i]); exit(0); }

Page 13 Environment Variables (1/2) 환경 변수 (environment variables) 는 부모 프로세스에서 자식 프로세스로 전달된다. 일반적으로, “.login” 또는 “.cshrc” 파일에서 환경 변수를 설정한다. 환경변수 선언 형식 : 이름 = 값 $ env USER=ysmoon LOGNAME=ysmoon HOME=/home/prof/ysmoon PATH=/bin:/usr/bin:/usr/local/bin:/usr/ccs/bin:/usr/ucb:/usr/ope nwin/bin:/etc:. SHELL=/bin/csh...

Page 14 Environment Variables (2/2)

Page 15 Environment List (1/2) 전역 변수 environ 을 이용하여 환경 변수에 접근한다. extern char ** environ; 각 항목은 " 환경 변수 이름 = 값 " 의 형식을 가진다. 각 문자열은 '\0' 로 끝난다. 환경 변수 리스트의 마지막은 NULL 포인터 argv 와 같은 구조이다.

Page 16 Environment List (2/2) "USER=ysmoon" "LOGNAME=ysmoon" "HOME=/home/prof/ysmoon" "PATH=/bin:/usr/local…" "MAIL =/var/mail/ysmoon" " SHELL=/bin/csh" NULL environ: environment pointer environment list environment strings...

Page 17 getenv() 환경 변수 리스트에서 이름이 name 인 것을 찾아서, 해당 값 ( 스트링 ) 에 대한 포인터를 리턴한다. 실패하면 NULL 포인터를 리턴 #include char *getenv(const char *name); Returns : pointer to value associated with name, NULL if not found

Page 18 putenv() 환경 변수를 추가한다 str 은 "name=value" 형식의 문자열 성공적으로 실행된 경우 0 을 리턴 같은 이름의 환경 변수가 이미 있다면 새 값으로 변경된다 #include int putenv(const char *str); Returns: 0 if OK, nonzero on error

Page 19 setenv(), unsetenv() setenv() 는 환경 변수 “name = value” 를 등록한다. name 의 환경변수가 이미 있을 경우 rewrite != 0 이면 새 값으로 변경되고, rewrite == 0 이면 값이 변경되지 않는다. unsetenv() 는 환경 변수 “name” 을 제거한다. #include int setenv(const char *name, const char *value, int rewrite); Returns: 0 if OK, nonzero on error void unsetenv(const char *name);

Page 20 Env Manipulation Example (1/2)

Page 21 Env Manipulation Example (2/2) Why not change ???

Page 22 Memory Layout of a C Program (1/2) uninitialized data (bss) stack heap initialized data text high address low address command-line arguments and environment variables initialized to zero by exec read from program file by exec

Page 23 Text Segment Machine instructions (read-only, sharable) Initialized Data Segment e.g. int maxcount = 99; (initialized) Uninitialized Data Segment (bss: block started by symbol) e.g. long sum[1000]; Stack automatic variables, temporary variables, return address, caller's environment (registers) Heap dynamic memory allocation (e.g., malloc()) Memory Layout of a C Program (2/2)

Page 24 Static Linking Library 사용된 라이브러리 루틴들이 ( 예 : printf) 실행파일에 추가된다 실행파일 크기 증가 Shared Library 실행파일에 라이브러리 루틴들을 포함하지 않는다. 공용의 메모리에 라이브러리 루틴을 로드하고 이를 공유한다. 프로그램 크기 감소 처음 실행될 때 오버헤드 발생 ( 메모리에 Loading 하는 과정이 필요할 수 있음 ) 라이브러리가 Version-Up 되어도 실행파일을 다시 컴파일 하지 않아도 됨 Shared Libraries

Page 25 Memory Allocation (1/2) Dynamic allocation of memory from heap Provide suitable alignment ex) doubles must start at the addresses that are multiples of 8. #include void *malloc(size_t size); void *calloc(size_t nobj, size_t size); void *realloc(void *ptr, size_t newsize); returns: nonnull pointer if OK, NULL on error void free(void *ptr);

Page 26 Memory Allocation (2/2) malloc() allocates specified number of bytes ( 주어진 바이트 수를 할당 ) initial value of memory is indeterminate ( 초기 값은 결정되지 않음 ) calloc() allocates specified number of objects of specified size ( 주어진 크기의 객체를 주어진 개수만큼 할당 ) initialized to all 0 bits ( 초기 값은 0 으로 결정 ) realloc() changes size of previously allocated memory ( 기 할당된 메모리 영역에 추가 할당 ) initial value of new area is indeterminate ( 새 영역의 초기 값은 결정되지 않음 )

Page 27 예제 : alloc.c #include // alloc.c int main() { struct _cbuf { char buf[12]; } *cbuf; char *mbuf; if((mbuf = (char *)malloc(12)) == (char *)0) { perror("malloc():"); exit(-1); } strcpy(mbuf, "Kangwon"); if((cbuf = (struct _cbuf *)calloc(2, sizeof(struct _cbuf))) == (struct _cbuf *)0) { perror("calloc():"); exit(-1); } strcpy(cbuf->buf, " University"); if((mbuf = (char *)realloc(mbuf, 24)) == (char *)0) { perror("realloc():"); exit(-1); } strcat(mbuf, " National"); printf("%s%s\n", mbuf, cbuf); free(mbuf); free(cbuf); }