Presentation is loading. Please wait.

Presentation is loading. Please wait.

[Unix Programming] Process Basic Young-Ju, Han

Similar presentations


Presentation on theme: "[Unix Programming] Process Basic Young-Ju, Han"— Presentation transcript:

1 [Unix Programming] Process Basic Young-Ju, Han

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

3 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

4 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

5 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 ); }

6 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

7 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

8 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 $

9 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

10 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

11 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

12 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] ) ; }

13 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

14 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 를 삭제

15 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)

16 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

17 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

18 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);// 할당된 메모리를 다시 시스템에 반환할때

19 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 내에서는 접근 가능

20 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 ?


Download ppt "[Unix Programming] Process Basic Young-Ju, Han"

Similar presentations


Ads by Google