[Unix Programming] Process Basic Young-Ju, Han

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.
Chapter 7 Process Environment Chien-Chung Shen CIS, UD
LINUX System Process (additional slides)
Spring 2005, Gülcihan Özdemir Dağ Lecture 12, Page 1 BIL104E: Introduction to Scientific and Engineering Computing, Spring Lecture 12 Outline 12.1Introduction.
Pointers A pointer is a reference to another variable (memory location) in a program –Used to change variables inside a function (reference parameters)
1 Lecture13: Other C Topics 12/17/2012. Topics Variable-length argument lists Pointers to functions Command-line arguments Suffixes for integer and floating-point.
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.
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.
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.
Kernighan/Ritchie: Kelley/Pohl:
Memory and Files Dr. Andrew Wallace PhD BEng(hons) EurIng
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:
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.
UNIX Process Control Bach 7 Operating Systems Course Hebrew University Spring 2007.
What does this program do ? #include int main(int argc, char* argv[]) { int i; printf("%d arguments\n", argc); for(i = 0; i < argc; i++) printf(" %d: %s\n",
C and Data Structures Baojian Hua
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.
Memory Layout C and Data Structures Baojian Hua
Shell (Part 1). Process r A process is an instance of an application running r If there are two instances of an application running then there are two.
Security Exploiting Overflows. Introduction r See the following link for more info: operating-systems-and-applications-in-
Fundamentals CIS 552. Fundamentals Low-level I/O (read/write using system calls)  Opening/Creating files  Reading & Writing files  Moving around in.
Dynamic Memory Allocation The process of allocating memory at run time is known as dynamic memory allocation. C does not Inherently have this facility,
6. More on Pointers 14 th September IIT Kanpur C Course, Programming club, Fall
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.
More on UART Interrupts; System Calls Reference on Interrupt Identification Register(IIR) slide 17 of
10/29/2015 Asst.Prof.Muhammed Cinsdikici 1 Network Programming UBI 510 Chapter 1.
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.
1 File Handling. 2 Storage seen so far All variables stored in memory Problem: the contents of memory are wiped out when the computer is powered off Example:
(language, compilation and debugging) David 09/16/2011.
Memory Layout, File I/O Bryce Boe 2013/06/27 CS24, Summer 2013 C.
CS415 C++ Programming Takamitsu Kawai x4212 G11 CERC building WV Virtual Environments Lab West Virginia University.
Programs and Processes Jeff Chase Duke University.
Copyright ©: Nahrstedt, Angrave, Abdelzaher
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)
Process Related System Calls By Neha Hulkoti & Kavya Bhat.
Basic of Buffer Over Flow
Using System Calls (Unix) Have to tell compiler (if C/C++) where to find the headers, etc. – i.e., the “include” files May have to tell compiler where.
“Success consists of going from failure to failure without loss of enthusiasm.” Winston Churchill.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 9.
Chapter 7 Process Environment Chien-Chung Shen CIS/UD
Stack and Heap Memory Stack resident variables include:
Protection of System Resources
Command Line Arguments
Linux Processes & Threads
Using Processes.
Unix Process Course code: 10CS62 Prepared by : Department of CSE.
Chapter 14 - Advanced C Topics
System Structure and Process Model
Dynamic Memory Allocation
Memory Allocation CS 217.
File Handling.
Process Programming Interface
The Environment of Unix Process
EENG212 – Algorithms & Data Structures Fall 07/08 – Lecture Notes # 5b
Presentation transcript:

[Unix Programming] Process Basic Young-Ju, Han

2007 UNIX Programming 2 Contents  Introduction  main Function  Process Termination  Command-line Arguments  Environment List  Memory Layout of a C Program

2007 UNIX Programming 3 main Function (1)  The prototype of the main function. int main(int argc, char *argv[]);  You did make only main(), but there are some more code in a.out C start-up code : doing initializations for the process and call exit(main(argc, argv)); C start-up code Doing initialization ; exit( main(argc,argv)) ; main( int argc, char* argv[] )) { … return 0 ; } a.out

2007 UNIX Programming 4 main Function (2)  How a C Program starts. You enter “a.out” on the shell prompt  $ a.out Shell forks itself and duplicates itself The duplicated shell calls  exec(“a.out”) The duplicated shell is replaced with “a.out” “a.out” runs Shell : $ a.out Shell fork a.out exec

2007 UNIX Programming 5 Process Termination (1)  Process terminations Normal  Return from main  Calling exit  Calling _exit Abnormal  calling abort  terminated by a signal main() { printf(“hello, world\n”); exit( 0 ); } int main( void ) { printf(“hello, world\n”); return 0 ; } main() { printf(“hello, world\n”); _exit( 0 ); }

2007 UNIX Programming 6 Process Termination (2)  exit #include void exit(int status); C library function Perform certain cleanups and return to the kernel closing all open file descriptors calling of all exit handlers (clean-up actions)  _exit #include void _exit(int status); System call Return to the kernel immediately

2007 UNIX Programming 7 Process Termination (3)  Prototype of atexit() function ANSI C 에서 exit 에 의해 자동으로 call 되는 function 을 32 개까 지 등록할 수 있음 ( 즉, exit handlers) 등록한 역순으로 call 됨 등록한 횟수만큼 call 됨 #include int atexit( void (*func) (void)); returns: 0 if OK, nonzero on error

2007 UNIX Programming 8 Process Termination (4)  Example of atexit() #inlcude #include static void my_exit1(void), my_exit2(void) ; int main( void ) { atexit( my_exit2 ) ; atexit( my_exit1 ) ; printf( "main is done\n" ) ; return 0 ; } static void my_exit1( void ) { printf( "first exist handler\n" ) ; } static void my_exit2( void ) { printf( "second exist handler\n" ) ; } $ a.out main is done first exit handler second exit handler $

2007 UNIX Programming 9 Process Termination (5) kernel exit function user functions main function C start-up routine exit handler standard I/O cleanup (via fclose)... _exit exec call return exit call return _exit user process

2007 UNIX Programming 10 Command-Line arguments  The command-line arguments passed to the main function via two parameters int argc and char *argv[].  Example. int main(int argc, char *argv[]) { int i; printf("argc = %d\n", argc); for(i=0; i<argc; i++) printf("argv[%d] = %s\n", i, argv[i]); return 0; } $ a.out hello world argc = 3 argv[0] = a.out argv[1] = hello argv[2] = world argc 3 argv \0 a.out\0 hello\0 world\0

2007 UNIX Programming 11 Environment Lists(1)  environment a collection of null-terminated strings  represented a null-terminated array of character pointers  name=value \ 0 int main(int argc, char *argv[], char *envp[]){ while(*envp) printf(“%s\n”, *envp++); return 0; } HOME=/usr/home/kmjsh PATH=:/bin:/usr:/usr/include SHELL=/bin/sh

2007 UNIX Programming 12 Environment Lists(2)  A global variable extern char **environ  Example  POSIX.1 은 main 의 third argument 대신에 environ 사용을 권함  특정 environment variable 에 접근하기 위해서는 getenv, putenv 를 사용 HOME=/home/stevens\0 PATH=:/bin:/usr/bin\0 SHELL=/bin/sh\0 environ \0 USER=stevens\0 #include extern char **environ ; main() { int i ; for( i = 0 ; environ[i] ; i++ ) printf( "%s\n", environ[i] ) ; }

2007 UNIX Programming 13 Environment Lists(3)  getenv To get environment lists  putenv To set environment lists int main(){ printf(“PATH=%s\n”, getenv(“PATH”)); if ( putenv(“NEW=val”) != 0 ) exit(1); printf(“NEW=%s\n”, getenv(“NEW”)); return 0; } #include char * getenv(const char *name); int putenv(char* string); String format “NAME=VALUE\0” Ex) “PATH=:/bin:/usr:/usr/include” 0 :success Non-zero : fail (ENOMEM) Value pointer : success NULL : not present

2007 UNIX Programming 14 Environment Lists(4) #include int setenv(const char *name, const char* value, int rewrite); 0 : not changed Non-zero : changed 0 :success -1 : fail #include void unsetenv (const char *name);  setenv name 이 존재하지 않으면 value 로 설정, 존재하고 rewrite 가 0 이 면 갱신하지 않고, 0 이 아니면 갱신  unsetenv name variable 를 삭제

2007 UNIX Programming 15 Memory Layout of a C Program (1)  Memories 영역들 text:  CPU 에 의해 수행되는 machine instructions data:  initialized global and static variables. 예 ) int maxcount = 99; bss:  uninitialized global and static variables.  exec 에 의해 0 or null 로 초기화 예 ) long sum[1000]; stack:  automatic (local) and temporary variables of each function. 프로그램 실행 중 할당된다. 함수의 처음에 할당되 고 끝나면 소멸된다. heap:  dynamically allocated area. (malloc, calloc)

2007 UNIX Programming 16 stack heap Memory Layout of a C Program (2) low address High address Initialized to 0 by exec read from program file by exec Command-line arg & environ. Var. uninitialized data (bss) initialized data text $ size /usr/bin/cc /bin/sh text data bss dec hex filename eed /usr/bin/grep cfc /bin/sh

2007 UNIX Programming 17 Memory Layout of a C Program (3) func(char *str) { char buf[16]; …. strcpy(buf, str); …. } main(int argc, char *argv[]) { …. func(argv[1]) …. } buf[16] SFP RET argv[1] main 변수 SFP RET … Local variable Stack frame pointer Return address argument low address high address  Stack structure

2007 UNIX Programming 18 Memory Layout of a C Program (4)  3 types of memory allocation functions malloc  allocate a specific number of bytes of memory calloc  allocate space for a specified number of objects of a specified size  The space is initialized to all 0 bits realloc  Change the size of a previously allocated area (increase, decrease)  Prototypes. #include void *malloc(size_t size); void *calloc(size_t nobj, size_t size); void *realloc(void *ptr, size_t newsize); void free(void *ptr);// 할당된 메모리를 다시 시스템에 반환할때

2007 UNIX Programming 19 Memory Layout of a C Program (5)  Global 변수 프로그램의 어디서나 접근 가능한 변수, Data 영역 또는 BSS 에 할당  Local 변수 Function 내부에서 정의된 변수  Function 내에서 선언된 Static 변수 Stack 이 아닌 Data 영역 또는 BSS 에 할당되고, Function 이 call 과 return 에 상관없이 항상 하나만이 존재  Function 밖에서 선언된 Static 변수 Data 영역 또는 BSS 에 할당되며, File 내에서는 접근 가능

2007 UNIX Programming 20 Memory Layout of a C Program (6)  Look at this code: can you differentiate these? int g_i ; int gi_i = 100 ; main( int argc, char *argv[] ) { int l_i ; char *ptr = malloc( 100 ) ; } $ size a.out text data bss dec hex filename b2 a.out Can you tell me which variable will be allocated into which area? How can I know the size of each area ?