Network Programming processes & signals

Similar documents
2009년 상반기 사업계획

<4D F736F F F696E74202D FC7C1B7CEBCBCBDBA20BBFDBCBAB0FA20BDC7C7E0205BC8A3C8AF20B8F0B5E55D>

Microsoft PowerPoint - 10_Process

ABC 11장

1장. 유닉스 시스템 프로그래밍 개요

좀비프로세스 2

6주차.key

제9장 프로세스 제어

<4D F736F F F696E74202D20B8AEB4AABDBA20BFC0B7F920C3B3B8AEC7CFB1E22E BC8A3C8AF20B8F0B5E55D>

System Programming Lab

Microsoft PowerPoint - Lecture_Note_7.ppt [Compatibility Mode]

<C1A63130C0E5C7C1B7CEBCBCBDBA2E687770>

/chroot/lib/ /chroot/etc/

Microsoft PowerPoint - 10_Signal

10.

Chap04(Signals and Sessions).PDF

제1장 Unix란 무엇인가?

Microsoft PowerPoint - chap9 [호환 모드]

Microsoft PowerPoint - 09-Pipe

제1장 Unix란 무엇인가?

Microsoft PowerPoint - ch09_파이프 [호환 모드]

2009년 상반기 사업계획

chap12(process).hwp

강의10

슬라이드 1

리눅스 프로세스 관리

<4D F736F F F696E74202D BDC3B1D7B3CEB0FA20BDC3B1D7B3CE20C3B3B8AE2E707074>

금오공대 컴퓨터공학전공 강의자료

임베디드시스템설계강의자료 6 system call 2/2 (2014 년도 1 학기 ) 김영진 아주대학교전자공학과

Microsoft PowerPoint - SP6장-시그널.ppt [호환 모드]

슬라이드 1

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션

3. 다음장에나오는 sigprocmask 함수의설명을참고하여다음프로그램의출력물과그출력물이화면이표시되는시점을예측하세요. ( 힌트 : 각줄이표시되는시점은다음 4 가지중하나. (1) 프로그램수행직후, (2) kill 명령실행직후, (3) 15 #include <signal.

슬라이드 1

고급 프로그래밍 설계

Microsoft PowerPoint - chap6 [호환 모드]

chap 5: Trees

Microsoft PowerPoint - chap02-C프로그램시작하기.pptx

C 프로그래밊 개요

PowerPoint 프레젠테이션

제 14 장포인터활용 유준범 (JUNBEOM YOO) Ver 본강의자료는생능출판사의 PPT 강의자료 를기반으로제작되었습니다.

< E20C6DFBFFEBEEE20C0DBBCBAC0BB20C0A7C7D12043BEF0BEEE20492E707074>

Microsoft PowerPoint oshw1.ppt [호환 모드]

[ 마이크로프로세서 1] 2 주차 3 차시. 포인터와구조체 2 주차 3 차시포인터와구조체 학습목표 1. C 언어에서가장어려운포인터와구조체를설명할수있다. 2. Call By Value 와 Call By Reference 를구분할수있다. 학습내용 1 : 함수 (Functi

Microsoft PowerPoint - ch07 - 포인터 pm0415

PowerPoint 프레젠테이션

2009년 상반기 사업계획

Microsoft PowerPoint - additional01.ppt [호환 모드]

쉽게 풀어쓴 C 프로그래밍

PowerPoint 프레젠테이션

The Pocket Guide to TCP/IP Sockets: C Version

Microsoft PowerPoint oshw1.ppt [호환 모드]

gdb 사용법 Debugging Debug라는말은 bug를없앤다는말이다. Bug란, 컴퓨터프로그램상의논리적오류를말하며, 이것을찾아해결하는과정이바로, debugging이다. 초기컴퓨터들은실제벌레가컴퓨터에들어가서오작동을일으키는경우가있었다고하며, 여기서 debug 이라는말이

Microsoft PowerPoint oshw1&2.ppt [호환 모드]

K&R2 Reference Manual 번역본

제8장 프로세스

제8장 프로세스

제1장 Unix란 무엇인가?

Microsoft PowerPoint - ch10 - 이진트리, AVL 트리, 트리 응용 pm0600

11장 포인터

02.Create a shellcode that executes "/bin/sh" Excuse the ads! We need some help to keep our site up. List Create a shellcode that executes "/bin/sh" C

Microsoft PowerPoint - chap06-5 [호환 모드]

3. 다음장에나오는 sigprocmask 함수의설명을참고하여다음프로그램의출력물과그출력물이화면이표시되는시점을예측하세요. ( 힌트 : 각줄이표시되는시점은다음 6 가지중하나. (1) 프로그램수행직후, (2) 5 초후 (3) 10 초후 (4) 15 #include <signa

Microsoft PowerPoint - chap13-입출력라이브러리.pptx

untitled

설계란 무엇인가?

C++ Programming

A Dynamic Grid Services Deployment Mechanism for On-Demand Resource Provisioning

제12장 파일 입출력

Sena Technologies, Inc. HelloDevice Super 1.1.0

Poison null byte Excuse the ads! We need some help to keep our site up. List 1 Conditions 2 Exploit plan 2.1 chunksize(p)!= prev_size (next_chunk(p) 3

<4D F736F F F696E74202D FB8DEB8F0B8AE20B8C5C7CE205BC8A3C8AF20B8F0B5E55D>

슬라이드 1

PowerPoint 프레젠테이션

Microsoft PowerPoint - chap10-함수의활용.pptx

<322EBCF8C8AF28BFACBDC0B9AEC1A6292E687770>

Microsoft Word - FunctionCall

vi 사용법

본 강의에 들어가기 전

Microsoft PowerPoint - lab14.pptx

임베디드시스템설계강의자료 6 system call 1/2 (2014 년도 1 학기 ) 김영진 아주대학교전자공학과

11장 포인터

vi 사용법

2009년 상반기 사업계획

PowerPoint 프레젠테이션

13 주차문자열의표현과입출력

PowerPoint 프레젠테이션

목차 포인터의개요 배열과포인터 포인터의구조 실무응용예제 C 2

The Pocket Guide to TCP/IP Sockets: C Version

PowerPoint 프레젠테이션

Chapter #01 Subject

Microsoft Word - Network Programming_NewVersion_01_.docx

Microsoft PowerPoint - ch09 - 연결형리스트, Stack, Queue와 응용 pm0100

PowerPoint 프레젠테이션

PowerPoint Template

<4D F736F F F696E74202D20B8B6C0CCC5A9B7CEC7C1B7CEBCBCBCAD202839C1D6C2F7207E203135C1D6C2F >

The Pocket Guide to TCP/IP Sockets: C Version

슬라이드 1

Transcription:

Network Programming processes & signals

Processes in Linux Processes identifier 식별자 (PID, process identifier) 2 ~ 32768 정수값 1: init process Process functionalities Stack Space : 지역변수, 함수호출및반환등제어용 환경변수를위한환경공간 자체프로그램카운터관리

Process status 프로세스상태보기명령어 ps af, ps ax top, gtop System Process x, xx, xxx 자리수의프로세스 주로 booting 시생성 (init 에의해 ) 시스템의유지관리운영프로세스 프로세스의우선순위 Process scheduler 에의해프로세서를점유할권리 기준값 : 10 (gtop 에의해볼수있음 ) nice : 기준값 +10 으로변경 % nice pid renice : 우선순위변경 % renice pid

New process creation & running system() exec() fork()

system() #include <stdlib.h> int system(const char *string) *string 으로전달되는실행가능코드를실행 실행종료되면 shell 혹은 control 귀환 일반적으로 shell 에서직접명령어수행이타당 단, 프로그램속에서실행이필요한경우사용 참고 : background & foreground processes

system() : exam #include <stdlib.h> #include <stdio.h> int main() { printf("running ps with system\n") system("ps -ax"); printf("done.\n"); exit(0);

exec() 프로세스대체 Caller process 에서 Callee process 로 pid, 프로세스환경등이이전 이전프로세스의내용은임무끝 현재프로세스를 path 나 file 인수에지정된실행파일을실행하기위하여새로운프로세스로대체

exec() 프로세스시작방법과인수전달방법제공 관련함수 #include <unistd.h> char **environ; init execl() int execlp() int execle() int execv() int execvp() int execve()

exec() l(), l_() execl(),execlp(), execle() 알수없는개수의 argument 전달 Null pointer 로끝나는개수의인수전달받음 v(), v_() execv(), execvp() argv 전달 p() $PATH 환경변수검색 e() Environment 변수전달가능

exec() #include <unistd.h> extern char **environ; int execl(const char *path, const char *arg,...); int execlp(const char *file, const char *arg,...); int execv(const char *path, char *const argv[]); int execvp(const char *file, char *const argv[]); path 실행파일의경로로상대경로와절대경로모두사용할수있다. file 경로이름이아닌실행파일의이름이다. 반환값 호출이성공하면호출하는프로세스에서는반환값을받을수없다. 만약함수호출후 -1 이반환되면이는함수호출이실패했음을의미한다.

exec() #include <unistd.h> extern char **environ; int execl(const char *path, const char *arg,...); int execlp(const char *file, const char *arg,...); int execv(const char *path, char *const argv[]); int execvp(const char *file, char *const argv[]); arg argv path 나 file 로지정한실행파일을실행할때필요한명령어라인의옵션과인자이다. 한개이상을지정할수있으며마지막인자는반드시 NULL 포인터로지정해야한다. arg 와같은의미를가지나문자형포인터의배열로형태가다르다. 배열의마지막은 NULL 문자열로끝나야한다.

exec() exec() 계열의함수는지정한실행파일로부터프로세스를생성한다. Cf: fork 는실행중인프로세스로부터새로운프로세스를생성한다. exec() 계열함수의사용예 Shell prompt 상에서 ls 를실행하는것과비교 $ ls -l /etc... execlp("ls", "ls", "-l", etc", (char *)0); main 함수의 *argv[] 에저장되는문자열들과같다. 프로세스를생성하기위해선택된실행파일의이름이다.

exec() 호출프로세스와피호출프로세스 호출프로세스 (caller process) exec() 를실행하는프로세스 피호출프로세스 (callee process) exec() 에의해생성되는프로세스 exec() 를성공적으로호출한결과 호출프로세스는종료된다.( 즉프로세스대체!) 호출프로세스가메모리영역을피호출프로세스가차지한다. 호출프로세스의 PID 를피호출프로세스가물려받는다.

exec()

exec() : exec 계열함수의구분 함수이름에 p 가있고없고의차이 p 가없으면 경로 (path) 로실행파일을지정한다. p 가있으면 실행파일의이름만지정한다. 경로를지정하는경우 (p 가없을경우 ) 지정한 ( 상대 / 절대 ) 경로에서해당파일을찾는다. 파일의이름만지정하는경우 (p 가있을경우 ) shell 환경변수 PATH 에서지정한디렉터리를차례대로검색하여찾는다. 예 ) $ printenv PATH 환경변수 PATH 의값을출력한다.

execlp() #include <unistd.h> #include <stdio.h> int main() { printf("running ps with execlp\n"); execlp("ps", "ps", "-ax", 0); printf("done.\n"); exit(0);

execl() #include <unistd.h> main() { printf("before executing ls -l\n"); 인자의나열이끝났음을의미한다. execl("/bin/ls", "ls", "-l", (char *)0); printf("after executing ls -l\n"); exec 호출이성공하면실행되지않는다. ( 될수가없다.) $./a.out before executing ls -l -rwxr-xr-x 1 usp student 13707 Oct 24 21:57 ex07-03 $

execv() #include <stdio.h> main() { char *arg[] = {"ls", "-l", (char *)0; printf("before executing ls -l\n"); execv("/bin/ls", arg); printf("after executing ls -l\n"); 이름에 l 이포함된경우와 v 가포함된경우의차이점이다. $./a.out before executing ls -l -rwxr-xr-x 1 usp student 13707 Oct 24 21:57 ex07-04 $

exec() 사용예 #include <unistd.h> /* example parameters, argv[0] */ Const char *ps_argv[]={ ps, -ax, 0; Const char *ps_envp[]={ PATH=/bin:/usr/bin, TERM=xterm, 0; /examples of exec() calls */ execl( bin/ps, ps, -ax, 0); /* PATH 제공 */ execlp( ps, ps, -ax, 0); /* /bin 이 PATH 에존재가정 */ execv( /bin.ps, ps_argv); execvp( ps, ps_argv); execve( /bin/ps, ps_argv, ps_envp);

fork() : 프로세스복제 하나이상의함수를수행하는프로세스사용가능 process 혹은 thread 새로운프로세를복제 parent process <> child process Parent process 와속성을많이가지는새로운 child procss 환경을가짐 Caller 와비슷, 같은코드실행 자체데이타공간 / 환경 / file descriptor 가짐 Parent process 에서 fork() 후새로운 pid 반환 Child process 에는 0 을반환 실패할경우 -1 CHILD_MAX 에의해최대개수제한

fork() : 관련함수 프로세스를생성하고종료하는시스템호출 / 표준라이브러리함수 함수 의미 fork() 자신과완전히동일한프로세스를생성한다. wait() exit Child process 종료기다리기 종료에따른상태값을부모프로세스에게전달하며프로세스를종료한다. atexit exit 로프로세스를종료할때수행할함수를등록한다. _exit atexit 로등록한함수를호출하지않고프로세스를종료한다.

Relationship between parent process and child process / return values Process (running) fork() 새로운 PID 반환 0 을반환 Parent process (running continue) Child Process (running newly)

fork() #include <sys/types.h> #include <unistd.h> pid_t fork(void); pid_t fork 호출이성공하여자식프로세스가만들어지면부모프로세스에서는자식프로세스의프로세스 ID 가반환되고자식프로세스에서는 0을반환한다. fork 호출이실패하여자식프로세스가만들어지지않으면부모프로세스에서는 -1이반환된다. 프로세스는실행파일로존재하는프로그램으로부터생성되는것이일반적이다. 그러나, fork 를사용하면실행중인프로세스를복제하여새로운프로세스를생성할수있다.

fork() 예제 1 #include <sys/types.h> #include <unistd.h> #include <stdio.h> int main() { pid_t pid; char *message; int n; printf("fork program starting\n"); pid = fork(); switch(pid) { case -1: perror("fork failed"); exit(1); case 0: message = "This is the child"; n = 5; break; default: message = "This is the parent"; n = 3; break; for(; n > 0; n--) { puts(message); sleep(1); exit(0);

fork() 예제 1 결과 실행결과 #./a.out fork program starting This is the parent This is the child This is the parent This is the child This is the parent This is the child This is the child This is the child #

fork() 예제 2 #include <unistd.h> #include <stdlib.h> #include <sys/types.h> void cleanupaction(void); main() { 프로세스식별번호를저장한다. pid_t pid; int i; for(i = 0; i < 3; i++) { printf("before fork [%d]\n", i); sleep(1); pid = fork(); 자식프로세스를생성한다. pid 에는사직프로세스의식별번호가저장된다.

fork() 예제 2 if(pid > 0) { for( ; i < 7; i++) { printf("parent [%d]\n", i); sleep(1); 부모프로세스가수행하는 부분이다. clean-up-action을등록한 atexit(cleanupaction); 다. 자식프로세스가수행하는 else if(pid == 0) { 부분이다. for( ; i < 5; i++) { printf("child [%d]\n", i); sleep(1); ls 를실행하여새로운 execl("/bin/ls", "ls", "-l", (char *)0); 프로세스를생성한다. 자식프로세스생성에실패 else { 했을때실행되는부분이다. printf("fail to fork child process\n");

fork() 예제 2 exit(0); /* end of main */ void cleanupaction(void) exit 호출시실행될함수이다. (clean-upaction) { printf("clean-up-action\n");

fork() 예제 2 프로그램의실행결과 $./a.out before fork [0] before fork [1] before fork [2] parent [3] child [3] parent [4] -rwxr-xr-x 1 usp student 14456 Oct 26 00:31 ex07-01 parent [5] parent [6] clean-up-action $

fork() 부모 (parent) 프로세스와자식 (child) 프로세스 fork 를호출하여새로운프로세스를생성할때, fork 를호출하는쪽을부모프로세스라고하고새로생성된쪽을자식프로세스라고한다. 부모프로세스와자식프로세스는서로다른프로세스이다. 프로세스식별번호 (PID) 가서로다르다. 자식프로세스의부모프로세스식별번호 (PPID) 는자신을생성한부모프로세스가된다. 자식프로세스는부모프로세스가 fork 를호출하던시점의상태를그대로물려받는다. 프로그램코드 프로그램변수에저장되어있는데이터값 하드웨어레지스터의값 프로그램스택의값등등 fork 호출이후에부모와자식프로세스는자신들의나머지프로그램코드를수행한다.

parent / child process fork() 를사용한프로세스생성

fork() fork 를호출하는프로그램의구조 fork 를호출하는시점을기준으로, fork 를호출한이후에부모프로세스가할일과자식프로세스가할일을구분한다. fork 의반환값으로부모프로세스와자식프로세스를구분한다. pid = fork(); /* fork 호출이성공하면자식프로세스가생성된다. */ if(pid == 0) if(pid == 0) /* 자식프로세스가수행할부분 */ ; else if(pid > 0) /* 부모프로세스가수행할부분 */ ; else /* fork 호출이실패할경우수행할부분 */ ;

fork() #include <unistd.h> #include <sys/types.h> i); printf("before calling fork(%d)\n", main() { pid_t pid; int i = 0; i++; $./a.out before calling fork(1) parent process(0) child process(2) $ ++i); --i); pid = fork(); if(pid == 0) /* 자식프로세스가수행할부분 */ printf("child process(%d)\n", else if(pid > 0) else 부분 */ /* 부모프로세스가수행할부분 */ printf("parent process(%d)\n", /* fork 호출이실패할경우수행할 printf("fail to fork\n");

fork 와 exec 비교 프로세스의원본 셸명령줄의프로그램인자 부모 ( 또는호출 ) 프로세스의상태 자식 ( 또는피호출 ) 프로세스의메모리상의위치 프로세스생성후자식 ( 또는피호출 ) 프로세스의프로그램코드의시작지점 프로세스식별번호 (PID) 프로세스의원본인파일에대한권한 fork() 부모프로세스를복제하여새로운프로세스를생성한다. 새롭게지정할수없고부모프로세스의것을그대로사용한다. 자식프로세스를생성한후에도자신의나머지코드를실행한다. 부모프로세스와다른곳에위치한다. exec() 지정한프로그램 ( 파일 ) 을실행하여프로세스를생성한다. 필요할경우적용할수있다. 호출이성공할경우호출 (Caller) 프로세스는종료된다. 호출프로세스가있던자리를피호출프로세스가물려받는다. fork 호출이후부터수행된다. 프로그램의처음부터수행된다. 자식프로세스는새로운식별번호를할당받는다. 부모프로세스를복제하므로상관없다. 호출프로세스의식별번호를피호출프로세스가물려받는다. 실행파일에대한실행권한이필요하다.

fork & exec fork 와 exec 의비교 fork 자신과동일한자식프로세스만생성할수있다. 다른종류의프로세스를생성할수없다. 자식프로세스를생성하더라도자신은종료되지않는다. exec 자신과다른종류의프로세스를생성할수있다. 새로운프로세스를생성하면자신은종료된다. fork 와 exec 를함께사용하기 fork 를호출하여자식프로세스를생성한후에자식프로세스가 exec 를호출하여새로운프로세스를생성한다. 결과적으로, 부모프로세스는종류가다른자식프로세스를생성하고자신역시나머지작업을계속할수있다.

fork & exec #include <unistd.h> #include <sys/types.h> main() { pid_t pid; printf("hello!\n"); pid = fork(); if(pid > 0) { /* parent process */ printf("parent\n"); sleep(1); else if(pid == 0) { /* child process */ printf("child\n"); execl("/bin/ls", "ls", "-l", (char *)0); printf("fail to execute ls\n"); else printf("parent : fail to fork\n"); printf("bye!\n"); 부모프로세스는자식프로세스의생존여부에상관없이자신의나머지일을수행한다. 자식프로세스가 exec를호출하여새로운프로세스를생성한다. 새로운프로세스를생성하고자식프로세스는종료된다.

fork & exec $ /a.out hello! parent child -rwxr-xr-x 1 usp student 13856 Oct 25 15:56 ex07-07 bye! $

exit() 프로세스를종료하면서부모프로세스에게종료와관련된상태값을넘겨준다. #include <stdlib.h> void exit(int status); status 부모프로세스에게전달되는상태값으로 0~255(1 바이트 ) 의값이사용된다. 반환값없음 exit는프로세스를의도적으로종료시킨다. 이외에프로세스가종료하는경우는 더이상수행할문장이없거나 main 함수내에서 return문을수행할때이다. status의값은 0~255 사이의값으로각각에대한정해진의미가없다. 프로그램작성자가임의로정해서사용한다.

atexit() 프로세스가 exit 를호출하여종료할때수행되는함수들을등록한다. #include <stdlib.h> int atexit(void (*function)(void)); function atexit 로등록할함수의이름이다. 반환값 호출이성공하면 0 을반환하고, 실패하면 0 이아닌값을반환한다. function 함수의이름으로함수는 void function(void); 형으로정의되어야한다. 종료시마무리작업 (clean-up-action) 프로세스가종료할때깔끔한마무리를위해수행해야하는작업들 최대 32 개까지등록할수있다. ( 실제실행순서는등록순서의역순 )

atexit() #include <unistd.h> #include <stdlib.h> void func1(void); void func2(void); main() { printf("hello!\n"); atexit(func1); atexit(func2); printf("bye!\n"); exit(0); $ /a.out hello! bye! func2 func1 $ void func1(void) { printf("func1\n"); void func2(void) { printf("func2\n");

_exit () exit 함수와같지만 clean-up-action 을수행하지않는다. #include <unistd.h> void _exit(int status); status 반환값 부모프로세스에게전달되는상태값으로 0~255(1 바이트 ) 의값이사용된다. 없음 _exit 는 atexit 로 clean-up-action 에해당하는함수들을등록해놓았더라도종료할때이를수행하지않는다.

_exit() #include <unistd.h> #include <stdlib.h> $ /a.out hello! bye! $ void func1(void); void func2(void); main() { printf("hello!\n"); atexit(func1); atexit(func2); printf("bye!\n"); _exit(0); void func1(void) { printf("func1\n"); void func2(void) { printf("func2\n");

wait() : child process 대기 #include <sys/types.h> #include <sys/wait.h> pid_t wait(int *stat_loc); pid_t *stat_loc Child process 로부터반환되는 PID Child process 의종료시전달되는값 (main() or exit()) sys/wait.h 참조 Child process 가끝날때까지 parent proces 가기다림 Parent process vs child process running time, racing condition child process 가종료될때까지 parent process 는대기 return value: child process 의 pid return status: *stat_loc -> sys/wait.h 에상태정보에대한 return value 가있음

wait() : Exam #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <stdio.h> main() { pid_t pid; char *message; int n; int exit_code; printf("fork program starting\n"); pid = fork(); switch(pid) { case -1: exit(1); case 0: message = "This is the child"; n = 5; exit_code = 37; break; default: message = "This is the parent"; n = 3; exit_code = 0; break; for(; n > 0; n--) { puts(message); sleep(1); /* 아래코드에서 parent process 는 child process 가종료될때까지기다린다 */ if(pid) { int stat_val; pid_t child_pid; child_pid = wait(&stat_val); printf("child has finished: PID = %d\n", child_pid); if(wifexited(stat_val)) printf("child exited with code %d\n", WEXITSTATUS(stat_val)); else printf("child terminated abnormally\n"); exit (exit_code);

wait() : Exam 실행결과 #./a.out For programstarting This is the parent This is the child This is the parent This is the child This is the parent This is the child This is the child This is the child Child has finished: PID = 1234 Child exited with code 37 #

waitpid() : 특정 child process 대기 #include <sys/types.h> #include <sys/wait.h> pid_t waitpid(pid_t pid, init *stat_loc, int options); pid_t *stat_loc Child process 로부터반환되는 PID Child process 의종료시전달되는값 (main() or exit()) sys/wait.h 참조 Child process 가끝날때까지 parent proces 가기다림 특정 child process PID 전달하여기다림 parent process 에서특정 pid 의 child process 를대기 다수 child process 상황에서유용 Options : waitpid() 의동작을변경가능 option Ex: WNOHANG : parent process 의실행을중단하지않음

waitpid() 사용예 : waitpid( child_pid, (init *)0, WNOHANG); - no terminated/not stopped : return=0 OR PID, - in error case: return=-1, errno??

Zombie process fork() 한 child process 의종료를 parent process 는무작정기다린다 parent process 의 process table 은 child process 가정상종료, return 되지않으면삭제되지않음 비정상적으로프로세스가계속동작되는경우발생 표시 : zombie or defunct init process 에의해정리 system resource 를고갈시킬위험 강제정리 : by root # kill -9 PIDs

Zombie process 의예 #include <sys/types.h> #include <unistd.h> #include <stdio.h> main() { pid_t pid; char *message; int n; printf("fork program starting\n"); pid = fork(); switch(pid) { case -1: perror("fork failed"); exit(1); case 0: message = "This is the child"; n = 3; break; default: message = "This is the parent"; n = 5; break; for(; n > 0; n--) { puts(message); sleep(1); exit(0); 실행방법 #./a.out & 실행중에 ps 명령어로확인 # ps <zomebie> 혹은 <defunct> 로표시됨

Signal Signal 프로세스실행중예러등에의해발생되는 event 시스템, 혹은다른프로세스이의해특정프로세스에전달되어상태를변환시키는 event interrupt, process kill.. 프로그램예외상황처리중에서외부 signal 의처리부분필요 Signal 을받은프로세스는적절한대응을해야한다 무시, 바로종료, 열린파일닫기, 기본동작복구등등 Signal 을전달받은프로세스에서적절한대응을못할경우종료될수있음 일반적으로실행디렉토리에 core 파일을 dump Debugging 에유용한파일

singal() #include <signal.h> void (*signal(int sig, void(*func)(int)))(int); sig func 처리해야할 signal 특정 signal 발생시실행할함수

signal Signal name description SIGABORT 프로세스취소 SIGALRM 알람시계 SIGFPE 부종소수예외 SIGHUP 접속종료 SIGILL 부적절한지시어 SIGKILL 처리하거나무시할수없는상태, 종료 SIGPIPE Reader 가없는파이프에쓰기 SIGQUIT 터미널종료 SIGSEGV 부적절한메모리세그먼트접근 SIGTERM 종료 SIGUSR1 사용자정의 1 SIGUSR2 사용자정의 2 SIGINT 터미널에서인터럽트

Signal Exam #include <signal.h> #include <stdio.h> #include <unistd.h> void ouch(int sig) { printf("ouch! - I got signal %d\n", sig); (void) signal(sigint, SIG_DFL); main() { (void) signal(sigint, ouch); while(1) { printf("hello World!\n"); sleep(1); SIGINT : intrrupt(^c) 최초 ^C: ouch() call 두번째 ^C: ouch() 에서 SIG_DFL 에의해원래 SIGINT 의기능복구 -> 따라서 process terminate!