LinuxUNIX Programming APUE The Environment of a LinuxUnix

  • Slides: 32
Download presentation
Linux/UNIX Programming APUE (The Environment of a Linux/Unix Process) 문양세 강원대학교 IT대학 컴퓨터과학전공

Linux/UNIX Programming APUE (The Environment of a Linux/Unix Process) 문양세 강원대학교 IT대학 컴퓨터과학전공

강의 내용 APUE (Understanding of UNIX Processes) Process Start Process Termination Command-Line Arguments Environment

강의 내용 APUE (Understanding of UNIX Processes) Process Start Process Termination Command-Line Arguments Environment Variables Memory Layout of a C program Memory Allocation Page 2 UNIX System Programming by Yang-Sae Moon

Process Start Kernel user process APUE (Understanding of UNIX Processes) exec system call C

Process Start Kernel user process APUE (Understanding of UNIX Processes) exec system call C start-up routine call return int main(int argc, char * argv[]); Page 3 UNIX System Programming by Yang-Sae Moon

main() APUE (Understanding of UNIX Processes) int main(int argc, char *argv[]); • argc :

main() APUE (Understanding of UNIX Processes) 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 Page 4 UNIX System Programming by Yang-Sae Moon

Process Termination APUE (Understanding of UNIX Processes) Normal Termination • Return from main() •

Process Termination APUE (Understanding of UNIX Processes) Normal Termination • Return from main() • Calling exit() // w/ cleanup process • Calling _exit() // w/o cleanup process Abnormal Termination • Calling abort() • Terminated by a signal Page 5 UNIX System Programming by Yang-Sae Moon

exit() APUE (Understanding of UNIX Processes) #include <stdlib. h> void exit(int status); 프로세스를 정상적으로

exit() APUE (Understanding of UNIX Processes) #include <stdlib. h> void exit(int status); 프로세스를 정상적으로 종료한다. Cleanup Processing 을 수행한다. • 모든 열려진 스트림(파일 등)을 닫고, • 출력 버퍼의 내용을 디스크에 쓴다. status • the exit status of a process (프로세스의 리턴 값으로 이해할 수 있음) • 이 값은 Linux/Unix shell 에 의해서 사용됨 (Shell Programming에서 이용할 수 있음) Page 6 UNIX System Programming by Yang-Sae Moon

_exit() APUE (Understanding of UNIX Processes) #include <unistd. h> void _exit(int status); 프로세스를 정상적으로

_exit() APUE (Understanding of UNIX Processes) #include <unistd. h> void _exit(int status); 프로세스를 정상적으로 종료한다. Kernel로 즉시 리턴한다. (Cleanup Processing을 수행하지 않는다. ) Page 7 UNIX System Programming by Yang-Sae Moon

atexit() APUE (Understanding of UNIX Processes) #include <stdlib. h> void atexit(void (*func)(void)); returns: 0

atexit() APUE (Understanding of UNIX Processes) #include <stdlib. h> void atexit(void (*func)(void)); returns: 0 if OK, nonzero on error exit handler 를 등록한다. • 프로그램이 종료할 때(exit()이 호출되었을 때) 수행하는 함수들을 등록 • 프로세스당 32개까지 등록 가능함 func • An exit handler • A function pointer exit()은 exit handler들을 등록된 역순으로 호출한다. Page 8 UNIX System Programming by Yang-Sae Moon

C Program Start and Termination (do call return e ) exit main function(does not

C Program Start and Termination (do call return e ) exit main function(does not return) function xit C start-up routine n) r tu call return re e t re o _exit …… exit handler ca ll tu sn e o (d urn ret rn exit handler l cal x no it tr et u es call _exit user function return _exit APUE (Understanding of UNIX Processes) rn user process standard I/O cleanup exec kernel Page 9 UNIX System Programming by Yang-Sae Moon

예제: exit handlers (1/2) APUE (Understanding of UNIX Processes) /* doatexit. c */ static

예제: exit handlers (1/2) APUE (Understanding of UNIX Processes) /* doatexit. c */ static void my_exit 1(void), my_exit 2(void); int main(void) { if (atexit(my_exit 2) != 0) perror("can't register my_exit 2"); if (atexit(my_exit 1) != 0) perror("can't register my_exit 1"); printf("main is donen"); return 0; } static void my_exit 1(void) { printf("first exit handlern"); } static void my_exit 2(void) { printf("second exit handlern"); } Page 10 UNIX System Programming by Yang-Sae Moon

예제: exit handlers (2/2) APUE (Understanding of UNIX Processes) 실행 결과 Page 11 UNIX

예제: exit handlers (2/2) APUE (Understanding of UNIX Processes) 실행 결과 Page 11 UNIX System Programming by Yang-Sae Moon

Command-Line Arguments APUE (Understanding of UNIX Processes) exec() can pass command-line arguments to a

Command-Line Arguments APUE (Understanding of UNIX Processes) exec() can pass command-line arguments to a new program. • argc에 Argument 개수를, • argv에 Argument를 각각 전달한다. Part of normal operation of Linux/Unix Shells. argv[argc] is NULL. Page 12 UNIX System Programming by Yang-Sae Moon

예제: echoarg. c APUE (Understanding of UNIX Processes) #include <stdio. h> // echoarg. c

예제: echoarg. c APUE (Understanding of UNIX Processes) #include <stdio. h> // echoarg. c int main(int argc, char *argv[]) { int i; for (i = 0; i < argc; i++) /* echo all command-line args */ printf("argv[%d]: %sn", i, argv[i]); exit(0); } Page 13 UNIX System Programming by Yang-Sae Moon

Environment Variables (1/2) APUE (Understanding of UNIX Processes) 환경 변수(environment variables)는 부모 프로세스에서 자식

Environment Variables (1/2) APUE (Understanding of UNIX Processes) 환경 변수(environment variables)는 부모 프로세스에서 자식 프로세스로 전달된다. 일반적으로, “. login”, “. cshrc”, “. bashrc” 파일에서 환경 변수를 설정한다. 환경변수 선언 형식: 이름=값 $ env USER=ysmoon LOGNAME=ysmoon HOME=/home/prof/ysmoon PATH=/bin: /usr/local/bin: /usr/ccs/bin: /usr/ucb: /usr/openwin /bin: /etc: . SHELL=/bin/csh. . . Page 14 UNIX System Programming by Yang-Sae Moon

Environment Variables (2/2) Page 15 APUE (Understanding of UNIX Processes) UNIX System Programming by

Environment Variables (2/2) Page 15 APUE (Understanding of UNIX Processes) UNIX System Programming by Yang-Sae Moon

Environment List (2/2) environment pointer environ: APUE (Understanding of UNIX Processes) environment list environment

Environment List (2/2) environment pointer environ: APUE (Understanding of UNIX Processes) environment list environment strings "USER=ysmoon" "LOGNAME=ysmoon" "HOME=/home/prof/ysmoon" "PATH=/bin: /usr/local…" "MAIL =/var/mail/ysmoon" . . . "SHELL=/bin/csh" NULL Page 17 UNIX System Programming by Yang-Sae Moon

getenv() APUE (Understanding of UNIX Processes) #include <stdlib. h> char *getenv(const char *name); Returns

getenv() APUE (Understanding of UNIX Processes) #include <stdlib. h> char *getenv(const char *name); Returns : pointer to value associated with name, NULL if not found 환경 변수 리스트에서 이름이 name 인 것을 찾아서, 해당 값(스트링)에 대한 포인터를 리턴한다. 실패하면 NULL 포인터를 리턴 Page 18 UNIX System Programming by Yang-Sae Moon

putenv() APUE (Understanding of UNIX Processes) #include <stdlib. h> int putenv(const char *str); Returns:

putenv() APUE (Understanding of UNIX Processes) #include <stdlib. h> int putenv(const char *str); Returns: 0 if OK, nonzero on error 환경 변수를 추가한다 str은 "name=value" 형식의 문자열 성공적으로 실행된 경우 0을 리턴 같은 이름의 환경 변수가 이미 있다면 새 값으로 변경된다 Page 19 UNIX System Programming by Yang-Sae Moon

setenv(), unsetenv() APUE (Understanding of UNIX Processes) #include <stdlib. h> int setenv(const char *name,

setenv(), unsetenv() APUE (Understanding of UNIX Processes) #include <stdlib. h> int setenv(const char *name, const char *value, int rewrite); Returns: 0 if OK, nonzero on error void unsetenv(const char *name); setenv()는 환경 변수 “name = value”를 등록한다. name 의 환경변수가 이미 있을 경우 • rewrite != 0 이면 새 값으로 변경되고, • rewrite == 0 이면 값이 변경되지 않는다. unsetenv()는 환경 변수 “name”을 제거한다. Page 20 UNIX System Programming by Yang-Sae Moon

Env Manipulation Example (1/2) Page 21 APUE (Understanding of UNIX Processes) UNIX System Programming

Env Manipulation Example (1/2) Page 21 APUE (Understanding of UNIX Processes) UNIX System Programming by Yang-Sae Moon

Env Manipulation Example (2/2) APUE (Understanding of UNIX Processes) Why not change ? ?

Env Manipulation Example (2/2) APUE (Understanding of UNIX Processes) Why not change ? ? ? Page 22 UNIX System Programming by Yang-Sae Moon

Memory Layout of a C Program (1/2) high address APUE (Understanding of UNIX Processes)

Memory Layout of a C Program (1/2) high address APUE (Understanding of UNIX Processes) command-line arguments and environment variables stack heap uninitialized data (bss) initialized to zero by exec initialized data read from program file by exec text low address Each area will be explained in the next slide… Page 23 UNIX System Programming by Yang-Sae Moon

Memory Layout of a C Program (2/2) APUE (Understanding of UNIX Processes) Text Segment

Memory Layout of a C Program (2/2) APUE (Understanding of UNIX Processes) 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()) Page 24 UNIX System Programming by Yang-Sae Moon

Memory Allocation (1/2) APUE (Understanding of UNIX Processes) #include <stdlib. h> void *malloc(size_t size);

Memory Allocation (1/2) APUE (Understanding of UNIX Processes) #include <stdlib. h> 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); Dynamic allocation of memory from heap Provide suitable alignment • ex) doubles must start at the addresses that are multiples of 8. Page 26 UNIX System Programming by Yang-Sae Moon

Memory Allocation (2/2) APUE (Understanding of UNIX Processes) malloc() • allocates specified number of

Memory Allocation (2/2) APUE (Understanding of UNIX Processes) 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 UNIX System Programming by Yang-Sae Moon

예제: alloc. c APUE (Understanding of UNIX Processes) #include <stdio. h> // alloc. c

예제: alloc. c APUE (Understanding of UNIX Processes) #include <stdio. h> // alloc. c #include <string. h> #include <stdlib. h> 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%sn", mbuf, cbuf); free(mbuf); free(cbuf); } Page 28 UNIX System Programming by Yang-Sae Moon

예제: morealloc. c (1/3) APUE (Understanding of UNIX Processes) Page 29 UNIX System Programming

예제: morealloc. c (1/3) APUE (Understanding of UNIX Processes) Page 29 UNIX System Programming by Yang-Sae Moon

예제: morealloc. c (2/3) APUE (Understanding of UNIX Processes) Page 30 UNIX System Programming

예제: morealloc. c (2/3) APUE (Understanding of UNIX Processes) Page 30 UNIX System Programming by Yang-Sae Moon

예제: morealloc. c (3/3) APUE (Understanding of UNIX Processes) Page 31 UNIX System Programming

예제: morealloc. c (3/3) APUE (Understanding of UNIX Processes) Page 31 UNIX System Programming by Yang-Sae Moon

Homework#9 Page 32 UNIX System Programming by Yang-Sae Moon

Homework#9 Page 32 UNIX System Programming by Yang-Sae Moon