26
Linux/UNIX Programming Linux/UNIX Programming APUE APUE (The Environment of a UNIX (The Environment of a UNIX Process) Process) [Ch. 7] [Ch. 7] 최 최 최 최 최 최 최최최최최 최최최최최최최 최최최최최 최최최최최최최

Linux/UNIX Programming APUE (The Environment of a UNIX Process) [Ch. 7] 최 미 정 강원대학교 컴퓨터과학전공

  • Upload
    shina

  • View
    44

  • Download
    0

Embed Size (px)

DESCRIPTION

Linux/UNIX Programming APUE (The Environment of a UNIX Process) [Ch. 7] 최 미 정 강원대학교 컴퓨터과학전공. 강의 내용. APUE (Understanding of UNIX Processes). Process Start Process Termination Command-Line Arguments Environment Variables Memory Layout of a C program Memory Allocation. Process Start. - PowerPoint PPT Presentation

Citation preview

Page 1: Linux/UNIX Programming APUE  (The Environment of a UNIX Process)  [Ch. 7] 최 미 정 강원대학교 컴퓨터과학전공

Linux/UNIX ProgrammingLinux/UNIX Programming

APUE APUE (The Environment of a UNIX (The Environment of a UNIX

Process) Process) [Ch. 7][Ch. 7]

최 미 정최 미 정강원대학교 컴퓨터과학전공강원대학교 컴퓨터과학전공

Page 2: Linux/UNIX Programming APUE  (The Environment of a UNIX Process)  [Ch. 7] 최 미 정 강원대학교 컴퓨터과학전공

UNIX System ProgrammingPage 2

강의 내용강의 내용

Process Start

Process Termination

Command-Line Arguments

Environment Variables

Memory Layout of a C program

Memory Allocation

APUE (Understanding of UNIX Processes)

Page 3: Linux/UNIX Programming APUE  (The Environment of a UNIX Process)  [Ch. 7] 최 미 정 강원대학교 컴퓨터과학전공

UNIX System ProgrammingPage 3

Process StartProcess Start

Kernel exec system call

C start-up routineuser process

int main(int argc, char * argv[]);

call return

APUE (Understanding of UNIX Processes)

Page 4: Linux/UNIX Programming APUE  (The Environment of a UNIX Process)  [Ch. 7] 최 미 정 강원대학교 컴퓨터과학전공

UNIX System ProgrammingPage 4

main()main()

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

APUE (Understanding of UNIX Processes)

Page 5: Linux/UNIX Programming APUE  (The Environment of a UNIX Process)  [Ch. 7] 최 미 정 강원대학교 컴퓨터과학전공

UNIX System ProgrammingPage 5

Process TerminationProcess Termination

Normal Termination

• Return from main()

• Calling exit() // w/ cleanup process

• Calling _exit() // w/o cleanup process

Abnormal Termination

• Calling abort()

• Terminated by a signal

APUE (Understanding of UNIX Processes)

Page 6: Linux/UNIX Programming APUE  (The Environment of a UNIX Process)  [Ch. 7] 최 미 정 강원대학교 컴퓨터과학전공

UNIX System ProgrammingPage 6

exit()exit()

프로세스를 정상적으로 종료한다 .

Cleanup Processing 을 수행한다 .

• 모든 열려진 스트림 ( 파일 등 ) 을 닫고 ,

• 출력 버퍼의 내용을 디스크에 쓴다 .

status

• the exit status of a process ( 프로세스의 리턴 값으로 이해할 수 있음 )

• 이 값은 UNIX shell 에 의해서 사용됨 (Shell Programming 에서 이용할 수 있음 )

#include <stdlib.h>

void exit(int status);

APUE (Understanding of UNIX Processes)

Page 7: Linux/UNIX Programming APUE  (The Environment of a UNIX Process)  [Ch. 7] 최 미 정 강원대학교 컴퓨터과학전공

UNIX System ProgrammingPage 7

_exit()_exit()

프로세스를 정상적으로 종료한다 .

Kernel 로 즉시 리턴한다 .

(Cleanup Processing 을 수행하지 않는다 .)

#include <unistd.h>

void _exit(int status);

APUE (Understanding of UNIX Processes)

Page 8: Linux/UNIX Programming APUE  (The Environment of a UNIX Process)  [Ch. 7] 최 미 정 강원대학교 컴퓨터과학전공

UNIX System ProgrammingPage 8

atexit()atexit()

exit handler 를 등록한다 .

• 프로그램이 종료할 때 (exit() 이 호출되었을 때 ) 수행하는 함수들을 등록

• 프로세스당 32 개까지 등록 가능함

func

• An exit handler

• A function pointer

exit() 은 exit handler 들을 등록된 역순으로 호출한다 .

#include <stdlib.h>

void atexit(void (*func)(void)); returns: 0 if OK, nonzero on error

APUE (Understanding of UNIX Processes)

Page 9: Linux/UNIX Programming APUE  (The Environment of a UNIX Process)  [Ch. 7] 최 미 정 강원대학교 컴퓨터과학전공

UNIX System ProgrammingPage 9

C Program Start and C Program Start and TerminationTermination

APUE (Understanding of UNIX Processes)

retu

rn

call

exitfunction

userfunction

mainfunction

C start-uproutine

exit handler

exit handler

standard I/Ocleanup

kernel

user process

exit(does not return)exit

(does not return)

exit

(does n

ot retu

rn)

call

return

call

return

callreturn

……

_exit

exec

_exit

_exit

retu

rn

call

Page 10: Linux/UNIX Programming APUE  (The Environment of a UNIX Process)  [Ch. 7] 최 미 정 강원대학교 컴퓨터과학전공

UNIX System ProgrammingPage 10

예제예제 : exit handlers (1/2): 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");}

APUE (Understanding of UNIX Processes)

Page 11: Linux/UNIX Programming APUE  (The Environment of a UNIX Process)  [Ch. 7] 최 미 정 강원대학교 컴퓨터과학전공

UNIX System ProgrammingPage 11

예제예제 : exit handlers (2/2): exit handlers (2/2)APUE (Understanding of UNIX Processes)

실행 결과

Page 12: Linux/UNIX Programming APUE  (The Environment of a UNIX Process)  [Ch. 7] 최 미 정 강원대학교 컴퓨터과학전공

UNIX System ProgrammingPage 12

Command-Line ArgumentsCommand-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.

APUE (Understanding of UNIX Processes)

Page 13: Linux/UNIX Programming APUE  (The Environment of a UNIX Process)  [Ch. 7] 최 미 정 강원대학교 컴퓨터과학전공

UNIX System ProgrammingPage 13

예제예제 : echoarg.c: echoarg.c

#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]: %s\n", i, argv[i]); exit(0);}

APUE (Understanding of UNIX Processes)

Page 14: Linux/UNIX Programming APUE  (The Environment of a UNIX Process)  [Ch. 7] 최 미 정 강원대학교 컴퓨터과학전공

UNIX System ProgrammingPage 14

Environment Variables (1/2)Environment Variables (1/2)

환경 변수 (environment variables) 는 부모 프로세스에서 자식 프로세스로 전달된다 .

일반적으로 , “.login” 또는 “ .cshrc” 파일에서 환경 변수를 설정한다 .

환경변수 선언 형식 : 이름 = 값

APUE (Understanding of UNIX Processes)

$ envUSER=ysmoonLOGNAME=ysmoonHOME=/home/prof/ysmoonPATH=/bin:/usr/bin:/usr/local/bin:/usr/ccs/bin:/usr/ucb:/usr/

openwin/bin:/etc:.SHELL=/bin/csh......

Page 15: Linux/UNIX Programming APUE  (The Environment of a UNIX Process)  [Ch. 7] 최 미 정 강원대학교 컴퓨터과학전공

UNIX System ProgrammingPage 15

Environment Variables (2/2)Environment Variables (2/2)APUE (Understanding of UNIX Processes)

Page 16: Linux/UNIX Programming APUE  (The Environment of a UNIX Process)  [Ch. 7] 최 미 정 강원대학교 컴퓨터과학전공

UNIX System ProgrammingPage 16

Environment List (1/2)Environment List (1/2)

전역 변수 environ 을 이용하여 환경 변수에 접근한다 .

extern char ** environ;

각 항목은 " 환경 변수 이름 = 값 " 의 형식을 가진다 .

• 각 문자열은 '\0' 로 끝난다 .

• 환경 변수 리스트의 마지막은 NULL 포인터

argv 와 같은 구조이다 .

APUE (Understanding of UNIX Processes)

Page 17: Linux/UNIX Programming APUE  (The Environment of a UNIX Process)  [Ch. 7] 최 미 정 강원대학교 컴퓨터과학전공

UNIX System ProgrammingPage 17

Environment List (2/2)Environment List (2/2)APUE (Understanding of UNIX Processes)

"USER=ysmoon""LOGNAME=ysmoon""HOME=/home/prof/ysmoon""PATH=/bin:/usr/local…""MAIL =/var/mail/ysmoon"

"SHELL=/bin/csh"

NULL

environ:

environment pointer

environmentlist

environmentstrings

...

Page 18: Linux/UNIX Programming APUE  (The Environment of a UNIX Process)  [Ch. 7] 최 미 정 강원대학교 컴퓨터과학전공

UNIX System ProgrammingPage 18

getenv()getenv()

환경 변수 리스트에서 이름이 name 인 것을 찾아서 ,

해당 값 ( 스트링 ) 에 대한 포인터를 리턴한다 .

실패하면 NULL 포인터를 리턴

#include <stdlib.h>

char *getenv(const char *name);

Returns : pointer to value associated with name, NULL if not found

APUE (Understanding of UNIX Processes)

Page 19: Linux/UNIX Programming APUE  (The Environment of a UNIX Process)  [Ch. 7] 최 미 정 강원대학교 컴퓨터과학전공

UNIX System ProgrammingPage 19

putenv()putenv()

환경 변수를 추가한다

str 은 "name=value" 형식의 문자열

성공적으로 실행된 경우 0 을 리턴

같은 이름의 환경 변수가 이미 있다면 새 값으로 변경된다

#include <stdlib.h>

int putenv(const char *str); Returns: 0 if OK, nonzero on error

APUE (Understanding of UNIX Processes)

Page 20: Linux/UNIX Programming APUE  (The Environment of a UNIX Process)  [Ch. 7] 최 미 정 강원대학교 컴퓨터과학전공

UNIX System ProgrammingPage 20

setenv(), unsetenv()setenv(), unsetenv()

setenv() 는 환경 변수 “ name = value” 를 등록한다 .

name 의 환경변수가 이미 있을 경우

• rewrite != 0 이면 새 값으로 변경되고 ,

• rewrite == 0 이면 값이 변경되지 않는다 .

unsetenv() 는 환경 변수 “ name” 을 제거한다 .

#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);

APUE (Understanding of UNIX Processes)

Page 21: Linux/UNIX Programming APUE  (The Environment of a UNIX Process)  [Ch. 7] 최 미 정 강원대학교 컴퓨터과학전공

UNIX System ProgrammingPage 21

Memory Layout of a C Program Memory Layout of a C Program (1/2)(1/2)

APUE (Understanding of UNIX Processes)

uninitialized data(bss)

stack

heap

initialized data

text

high address

low address

command-line argumentsand environment variables

initialized to zero by exec

read from program file by exec

Each area will be explained in the next slide…

Page 22: Linux/UNIX Programming APUE  (The Environment of a UNIX Process)  [Ch. 7] 최 미 정 강원대학교 컴퓨터과학전공

UNIX System ProgrammingPage 22

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

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

Page 23: Linux/UNIX Programming APUE  (The Environment of a UNIX Process)  [Ch. 7] 최 미 정 강원대학교 컴퓨터과학전공

UNIX System ProgrammingPage 23

Static Linking Library

• 사용된 라이브러리 루틴들이 ( 예 : printf) 실행파일에 추가된다

• 실행파일 크기 증가

Shared Library

• 실행파일에 라이브러리 루틴들을 포함하지 않는다 .

• 공용의 메모리에 라이브러리 루틴을 로드하고 이를 공유한다 .

• 프로그램 크기 감소

• 처음 실행될 때 오버헤드 발생 ( 메모리에 Loading 하는 과정이 필요할 수 있음 )

• 라이브러리가 Version-Up 되어도 실행파일을 다시 컴파일 하지 않아도 됨

APUE (Understanding of UNIX Processes)Shared LibrariesShared Libraries

Page 24: Linux/UNIX Programming APUE  (The Environment of a UNIX Process)  [Ch. 7] 최 미 정 강원대학교 컴퓨터과학전공

UNIX System ProgrammingPage 24

Memory Allocation (1/2)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 <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 errorvoid free(void *ptr);

APUE (Understanding of UNIX Processes)

Page 25: Linux/UNIX Programming APUE  (The Environment of a UNIX Process)  [Ch. 7] 최 미 정 강원대학교 컴퓨터과학전공

UNIX System ProgrammingPage 25

Memory Allocation (2/2)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 26: Linux/UNIX Programming APUE  (The Environment of a UNIX Process)  [Ch. 7] 최 미 정 강원대학교 컴퓨터과학전공

UNIX System ProgrammingPage 26

예제예제 : alloc.c: alloc.c

#include <stdio.h> // 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);}

APUE (Understanding of UNIX Processes)