200 likes | 351 Views
[Unix Programming] Process Basic. Young-Ju, Han Email: yjhan@imtl.skku.ac.kr. Contents. Introduction main Function Process Termination Command-line Arguments Environment List Memory Layout of a C Program. main Function (1). The prototype of the main function.
E N D
[Unix Programming]Process Basic Young-Ju, Han Email: yjhan@imtl.skku.ac.kr
Contents • Introduction • main Function • Process Termination • Command-line Arguments • Environment List • Memory Layout of a C Program 2007 UNIX Programming
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
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 fork Shell Shell exec a.out 2007 UNIX Programming
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 ); } main() { printf(“hello, world\n”); exit( 0 ); } int main( void ) { printf(“hello, world\n”); return 0 ; } 2007 UNIX Programming
Process Termination (2) • exit • #include <stdlib.h> • 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 <unistd.h> • void _exit(int status); • System call • Return to the kernel immediately 2007 UNIX Programming
Process Termination (3) • Prototype of atexit() function • ANSI C에서 exit 에 의해 자동으로 call되는 function을 32개까지 등록할 수 있음(즉, exit handlers) • 등록한 역순으로 call됨 • 등록한 횟수만큼 call됨 #include <stdlib.h> int atexit( void (*func) (void)); returns: 0 if OK, nonzero on error 2007 UNIX Programming
Process Termination (4) • Example of atexit() #inlcude <stdlib.h> #include <stdio.h> static void my_exit1(void), my_exit2(void) ; int main( void ) { atexit( my_exit2 ) ; atexit( my_exit1 ) ; 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 first exit handler second exit handler $ 2007 UNIX Programming
Process Termination (5) user process exit handler user functions call exit return call return ... exit main function exit function exit handler _exit return call standard I/O cleanup (via fclose) exit C start-up routine _exit exec kernel 2007 UNIX Programming
3 argc a.out\0 argv hello\0 world\0 \0 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 2007 UNIX Programming
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
environ HOME=/home/stevens\0 PATH=:/bin:/usr/bin\0 SHELL=/bin/sh\0 \0 USER=stevens\0 Environment Lists(2) • A global variable extern char **environ • Example • POSIX.1은 main의 third argument대신에 environ 사용을 권함 • 특정 environment variable에 접근하기 위해서는 getenv, putenv를 사용 #include <stdio.h> extern char **environ ; main() { int i ; for( i = 0 ; environ[i] ; i++ ) printf( "%s\n", environ[i] ) ; } 2007 UNIX Programming
0 :success Non-zero : fail (ENOMEM) Value pointer : success NULL : not present Environment Lists(3) • getenv • To get environment lists • putenv • To set environment lists String format “NAME=VALUE\0” Ex) “PATH=:/bin:/usr:/usr/include” #include <stdlib.h> char * getenv(const char *name); int putenv(char* string); int main(){ printf(“PATH=%s\n”, getenv(“PATH”)); if ( putenv(“NEW=val”) != 0 ) exit(1); printf(“NEW=%s\n”, getenv(“NEW”)); return 0; } 2007 UNIX Programming
0 : not changed Non-zero : changed 0 :success -1 : fail Environment Lists(4) • setenv • name이 존재하지 않으면 value로 설정, 존재하고 rewrite가 0이면 갱신하지 않고, 0이 아니면 갱신 • unsetenv • name variable를 삭제 #include <stdlib.h> int setenv(const char *name, const char* value, int rewrite); #include <stdlib.h> void unsetenv (const char *name); 2007 UNIX Programming
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
Memory Layout of a C Program (2) High address Command-line arg & environ. Var. • $ size /usr/bin/cc /bin/sh • text data bss dec hex filename • 284 428 7917 1eed /usr/bin/grep • 87678 2778 11172 101628 18cfc /bin/sh stack heap uninitialized data (bss) Initialized to 0 by exec initialized data read from program file by exec text low address 2007 UNIX Programming
Memory Layout of a C Program (3) • Stack structure low address func(char *str) { char buf[16]; …. strcpy(buf, str); …. } main(int argc, char *argv[]) { …. func(argv[1]) …. } high address 2007 UNIX Programming
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 <stdlib.h> 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
Memory Layout of a C Program (5) • Global 변수 • 프로그램의 어디서나 접근 가능한 변수, <extern> • Data 영역 또는 BSS에 할당 • Local 변수 • Function 내부에서 정의된 변수 • Function내에서 선언된 Static 변수 • Stack이 아닌 Data 영역 또는 BSS에 할당되고, Function이 call과 return에 상관없이 항상 하나만이 존재 • Function밖에서 선언된 Static 변수 • Data 영역 또는 BSS에 할당되며, File 내에서는 접근 가능 2007 UNIX Programming
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 ) ; } Can you tell me which variable will be allocated into which area? $ size a.out text data bss dec hex filename 28198 9368 500 38066 94b2 a.out How can I know the size of each area ? 2007 UNIX Programming