슬라이드 1

Size: px
Start display at page:

Download "슬라이드 1"

Transcription

1 제 3 부프로그램의실행 I 7. 프로그램의실행기법 프로세스의일생 메모리관리 프로세스에의한메모리확보 프로세스간통신 프로세스환경 프로세스스케줄링

2 소개 프로그램이란컴퓨터가할일을명시한것이다. 결국컴퓨터의임무는프로그램을수행시킴으로서달성된다. 그러면어떻게프로그램을수행시키는것이효율적일까? 그해답이바로 프로세스 란개념을이용하는것이다. 프로세스 (process) 란프로그램을처리장치에서수행할때의모습이다. 이 모습 은실행중의프로그램의실체로서메모리상의코드, CPU 에서사용하는제반레지스터 ( 임시데이터 ), 운영체제가실행을위해필요로하는자료구조등을포함한다. 따라서컴퓨터의일차적인목표는이들프로세스를효율적으로관리하는것이다. 프로세스관리를위해서는프로세스에관련된자료구조의관리, 메모리관리, 프로세스스케줄링등의작업이필요하다. 이장에서는프로세스를중심으로한프로그램의실행과정과실행특성을살펴본다. 프로세스는컴퓨터의모든작업과연관되어있으므로프로세스를알면다른모든컴퓨터동작특성도파악할수있다. 그러므로프로세스에대한지식은컴퓨터의동작을이해하는데핵심이다. Spring 2010 System Programming (Shin) 2

3 7.1 프로세스의일생

4 Linux 의초기동작 1 단계 : init 프로세스의생성 로더 (loader) 에의해디스크상의커널프로그램을메모리에적재 커널은일련의프로세스를생성 마지막으로 /sbin/init 을 exec 하여 init 프로세스를생성 2 단계 : login 프로세스의생성 init 프로세스에의해각종프로세스가생성됨 디몬 (daemon) 프로세스의생성 daemon 프로세스란어느한단말 ( 혹은사용자 ) 에속하지않고배경에서서비스를제공하는서버 서버는통상컴퓨터가동작하는동안계속해서동작하면서클라이언트에게서비스를제공 login 프로세스의생성 login 프로세스는사용자로부터의로그인을받아들여사용자의 shell 프로그램을다시 exec 함 Spring 2010 System Programming (Shin) 4

5 [ 註 例 ] Linux 의초기동작 Linux 동작시키기 1 단계 1. 컴퓨터전원이켜지면레지스터들이미리정해진값으로설정되어 boot ROM 에저장된코드 (bootstrap loader) 를수행 2. 이부트로더가디스크블록 0 에있는 boot block 을메모리에적재 3. 이 boot block program 이커널라이브러리 ( 예 : /boot/vmlinux) 를적재. 적재후제어를이커널로넘김 4. 커널은 process 0 를직접만듦. 5. process 0 는자식프로세스로서 process 1 을생성 (fork) 6. process 1 은 /sbin/init 를 exec 함 Process 0 직접작성된최초의커널프로세스 Process 0 는자식프로세스로서 Process 1 을생성 (fork) Process 1 init exec Process 1 은 /sbin/init 을 exec 함 Spring 2010 System Programming (Shin) 5

6 [ 註 例 ] Linux 의초기동작 Linux 동작시키기 2 단계 1. init 프로세스는 daemon 을생성함 (fork 와 exec 이용 ) 2. 단말을위하여 getty 프로세스를생성함 (fork 와 exec 이용 ) 3. getty 프로세스는다시 login 프로세스를 exec 함 Process 0 Daemons e.g. ftpd, httpd init init getty login exec exec daemon 과 getty 생성 Spring 2010 System Programming (Shin) 6

7 프로세스의생성과종료 프로세스의생성과종료과정 fork, exec ( 선택적 ), wait, exit parent 시간 parent wait() fork() [ exec() ] child exit() Spring 2010 System Programming (Shin) 7

8 [ 註 例 ] 프로세스의생성과종료 #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> int main(int argc, char *argv[]) { pid_t pid; if (pid == 0) { /* child */ execl(argv[1], argv[1], argv[2], NULL); /* error if the next line is executed */ perror(argv[1]); exit(99); } else { /* parent */ int status; if (argc!= 3) { fprintf(stderr, "Usage:?\n", argv[0]); exit(1); } pid = fork(); if (pid < 0) { fprintf(stderr, "fork() failed\n"); exit(1); } /* to be continued */ } } waitpid(pid, &status, 0); printf("child (PID=%d) has exited: ", pid); /* may check the exit status to see how the child is terminated, and then take appropriate actions. */ exit(0); exec() 이정상적으로실행되는경우, 호출프로그램으로복귀하지않음 (no return) Spring 2010 System Programming (Shin) 8

9 Linux 프로세스의계통도 Linux 프로세스의상호관계 Process 0 init Daemons Login shell getty s Child Child Child Grandchild Grandchild Grandchild Spring 2010 System Programming (Shin) 9

10 [ 註 例 ] Linux 프로세스의상호관계 프로세스그룹 process group shell 을위한존재 signal 에대해그룹내의모든프로세스가반응 각프로세스는한개의프로세스그룹에속함. 통상, command pipeline 에속한프로세스들이같은그룹에속함 예 : ls grep id wc -w 프로세스 / 그룹의 id 획득및설정 getpid() [ 자신 ] tty4 getppid() [ 부모 ] getpgrp() [ 프로세스그룹 ] setpgid(): [ 프로세스그룹 id 변경 ] session process group session 사용자가한단말에서로그인해서마칠때까지의흐름을관리하기위한개념 즉, 한단말에서작업하던사용자가 logout 혹은중단하면어떻게할것인가? 로그인쉘로부터 ( 같은단말에서 ) 생성된모든프로세스그룹의집합 세션을생성한프로세스가 session leader ( 통상 shell) 가됨 세션 ID 는세션리더의 ID 한세션이종료하게되면, 이를 signal 에의해세션리더에게알림. 세션리더는소속프로세스그룹을중단시킴 (kill) 세션과연관된단말을제어단말 (controlling terminal) 이라함 만일 shell 이먼저중단되면? (init process takes up shell s position) Spring 2010 System Programming (Shin) 10

11 [ 註 例 ] Linux 프로세스의상호관계 Process groups linux> pstree -p (-p: pid 표시 ) Background init(1)-+-acpid(2108) -httpd(2605)-+-httpd(29741) -httpd(17157) -httpd(17158) `-httpd(23987) -sendmail(2572) acpid pid=2108 pgrp=2108 -sshd(2201)---sshd(12530)---sshd(12535)---bash(12536)---pstree(12644) httpd pid=29741 pgrp=2605 Background httpd pid=2605 pgrp=2605 httpd pid=17157 pgrp=2605 init pid=1 pgrp=0 httpd pid=17158 pgrp=2605 Background sendmail pid=2572 pgrp=2572 Foreground sshd pid=2201 pgrp=2201 shinhs@pts/1 sshd pid=12535 pgrp=12530 pstree pid=12644 pgrp=12644 Background shinhs sshd pid=12530 pgrp=12530 bash pid=12536 pgrp=12536 Spring 2010 System Programming (Shin) 11

12 디몬프로세스 Daemons 특징 배경 (background) 에서사용자와대화없이실행됨 시스템전체나사용자프로그램에주어진서비스를제공 디몬은일반적으로프로세스그룹 leader 이며 session leader 임 디몬의부모는 init process (pid=1) 디몬의생성절차 (1) fork() 에의해새로운 ( 자식 ) 프로세스생성. 부모프로세스는 exit (2) 새로운세션을생성 : setsid() 디몬이새로운세션의리더인동시에프로세스그룹의리더가됨 단말 (terminal) 과의연계를해제 : 더이상 controlling terminal 이없음 (3) root directory 를 cwd(current working directory) 로함 연계된파일시스템이없게하여파일시스템을제거해도영향이없음 (4) umask(user file creation mode mask) 를 0 으로함 디몬에서새로운파일을생성할때영향이없게함 (5) 부모프로세스로부터전달받은파일디스크립터를모두닫음 통상, stdin, stdout, stderr umask: 파일의접근허용 (permission) 모드를새로설정할때사용하는 mask. 예 : 사용자의 umask가 8진법으로 042라면, 새파일을만들때 777 (default) (umask) = 735 ( 새파일의접근허용값 ) Spring 2010 System Programming (Shin) 12

13 /* lpedated.c Simple timestamping daemon */ #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <fcntl.h> #include <errno.h> #include <unistd.h> #include <time.h> #include <syslog.h> int main(void) { pid_t pid, sid; time_t timebuf; int fd, len; /* Open the system log */ openlog("lpedated", LOG_PID, LOG_DAEMON); pid = fork(); (1) if(pid < 0) { syslog(log_err, "%s\n", perror); exit(exit_failure); } [ 註 例 ] Daemons if(pid > 0) /* In the parent, let's bail */ exit(exit_success); (1) /* In the child... */ /* First, start a new session */ if((sid = setsid()) < 0) { (2) syslog(log_err, "%s\n", "setsid"); exit(exit_failure); } /* Next, make / the current dir */ if((chdir("/")) < 0) { (3) syslog(log_err, "%s\n", "chdir"); exit(exit_failure); } /* Reset the file mode */ umask(0); (4) /* Close stdin, etc. */ close(stdin_fileno); (5) close(stdout_fileno); close(stderr_fileno); } /* Finally, do our work */ len = strlen(ctime(&timebuf)); while(1) { char *buf = malloc(sizeof(char) * (len + 1)); if(buf == NULL) { syslog(log_err, "malloc"); exit(exit_failure); } if((fd = open("/var/log/lpedated.log", O_CREAT O_WRONLY O_APPEND, 0600)) < 0) { syslog(log_err, "open"); exit(exit_failure); } time(&timebuf); strncpy(buf, ctime(&timebuf), len + 1); write(fd, buf, len + 1); close(fd); sleep(60); } closelog(); exit(exit_success); Kurt Wall, Linux Programming by Examples. Que, 2000, pp Spring 2010 System Programming (Shin) 13

14 7.2 메모리관리

15 프로그램의실행과메모리 프로그램의적재 (loading) 및실행 적재 : 디스크상의프로그램파일을주기억으로옮김. 실행 : 메모리상의코드및데이터를참조하여야함. 메모리와관련된문제점 물리메모리의기억공간이해당파일전체를수용하기에충분하지않을수있음 디스크에서페이지단위로읽어와야함. 페이지가물리메모리의어디에위치하게될지모름 실행시참조하는메모리주소는가상기억의주소임 가상기억관리기법에의한해결책 물리메모리와가상기억 ( 혹은디스크공간 ) 을일정한크기의페이지단위로관리 물리메모리공간에맞추어, 디스크에서페이지단위로프로그램파일의필요한부분만을메모리에적재가능 가상주소공간과물리주소공간사이를연계하는주소변환작업을수행 - 주소사상 (mapping) 기법 Spring 2010 System Programming (Shin) 15

16 [ 註 例 ] 프로그램의실행과메모리 프로그램의적재시 프로그램 물리메모리 파일 페이지단위로디스크의프로그램을사용가능한물리메모리에적재. 이때, 물리메모리도디스크의페이지와같은크기의 블록 (block) 단위로구성됨 프로그램의실행시메모리주소의참조 프로그램 ( 가상주소공간 ) 주소변환메커니즘 물리메모리 ( 물리주소공간 ) CPU 가상주소 (virtual address) 물리주소 (physical address) Spring 2010 System Programming (Shin) 16

17 주소의변환 동기 가상기억의기억공간 ( 즉, 주소공간 ) 과물리메모리기억공간과의괴리 실행되기전까지는문제가없지만, 실행시디스크에저장된프로그램과데이터를주기억으로적재하여실행하여야함 왜냐하면, CPU 에서실행되는프로그램은가상기억의주소밖에모름 이들사이의불일치를어떻게해결하여야하는가 운영체제가실행중인프로그램을위해서가상기억주소를주기억주소로변환 주소변환 address translation 가상주소를물리주소로사상하는작업 주소공간의정의 가상주소공간 virtual address space V = {v: v 는정수, 0 v N 1} 물리주소공간 physical address space P = {p: p 는정수, 0 p M 1} 단, M N 주소변환함수 T 의정의 T: V P U ( 는공집합 ) T(v) : 이경우는가상주소 v 의데이터가물리메모리에존재하지않을때. 즉, 데이터가디스크에서주기억으로적재되지않았거나아예없는경우 이경우를 page fault 라부름 Spring 2010 System Programming (Shin) 17

18 주소의변환 주소포맷의구성 주소 : 페이지번호 + 페이지내에서의변위 (offset) 페이지크기 P = 2 p (bytes), 최대가상주소 N = 2 n, 최대물리주소 M = 2 m n 1 p p 1 0 virtual page number virtual page offset 가상주소 m 1 physical page number p p 1 physical page offset 0 물리주소 페이지테이블을이용한주소변환 가상페이지 페이지테이블 물리페이지 ( 실제메모리 ) 페이지테이블 (page table) 의구성 인덱스 (index): 가상페이지번호 페이지테이블엔트리 ( 내용 ): 물리페이지번호, 즉블록번호 단, 페이지내에서의오프셋은변하지않음 주소변환메커니즘의구현 memory management unit(mmu) 란하드웨어에의해구현됨 Spring 2010 System Programming (Shin) 18

19 [ 註 例 ] 주소의변환 처리과정 memory hit: 원하는페이지가주기억에존재할때 주소변환메커니즘을통하여참조주소에액세스 memory miss: 원하는페이지가주기억에없을때 이경우를 page fault 라함 운영체제가해당페이지를디스크에서가져오며, 그동안프로그램수행은중단됨. Hit CPU 1 MMU 2 Memory/ Cache 경우에따라서는, 일단주기억상의페이지를디스크에써넣은후삭제하고나서, 디스크에서원하는 페이지를가져올수있음 가상주소 물리주소 Miss CPU 1 MMU 4 Memory/ Cache 2 3 Disk 페이지폴트 2 I/O unit 2 Spring 2010 System Programming (Shin) 19

20 [ 註 例 ] 주소의변환 페이지테이블에주소변환기법의개념 프로세스마다별개의페이지테이블 프로그램에서사용하는모든페이지를포함하며테이블에대한인덱스가가상페이지번호가됨 테이블의내용 (entry) 해당가상페이지에대한물리페이지번호 페이지에대한정보 페이지의유효성 (valid) 여부표시. 즉해당페이지가주기억에존재하는지여부 접근권리 (access right) 필드는접근허용여부를표시 Page table base register n 1 p p 1 0 virtual page number virtual page offset 가상주소 valid? physical page no. 1 0x412a8f0 Page table access right m 1 p p 1 0 physical page number physical page offset 물리주소 Spring 2010 System Programming (Shin) 20

21 주소변환의고속화 페이지테이블이용의문제점 페이지테이블을접근하는것도메모리를한번접근하는것임. 즉, 메모리를두번접근해야원하는데이터를인출 2 page table index address Page table CPU 1 virtual address MMU 3 physical page number 4 physical address data Memory/ Cache Translation Lookaside Buffer (TLB) 고속메모리를이용한페이지테이블의고속화 메모리관리장치 (MMU) 내의소규모하드웨어캐쉬 즉, TLB 는캐쉬化된축소형페이지테이블로서주소변환을고속화함 Spring 2010 System Programming (Shin) 21

22 [ 註 例 ] 주소변환의고속화 TLB 를이용한주소변환 TLB hit 의경우 : 주소변환이완료되어물리메모리주소가결정됨 TLB miss 의경우 : 주기억에있는페이지테이블을참조하여주소변환 Miss 2 3 page table CPU 1 virtual address MMU TLB Hit 4 2 data Memory/ Cache 단, 페이지테이블은주기억에만위치한다고가정 Spring 2010 System Programming (Shin) 22

23 7.3 프로세스에의한메모리확보

24 Linux/C 에서메모리확보방법 접근방법 실행파일생성시에결정되는메모리크기를 data 및 bss 영역에확보 전역변수 (global variable), 함수, 등의정적인데이터에대한정적인할당 (static allocation) 실행파일생성시에결정되는메모리크기를스택영역에확보 로컬변수의정적인할당 실행시에결정되는메모리크기를히프 (heap) 영역에확보 프로그램실행시에 malloc() 함수를이용하여메모리를동적인할당 (dynamic allocation) 실행시에결정되는메모리크기를스택영역에확보 프로그램실행시에 alloca() 함수를이용하여스택공간을동적할당 Spring 2010 System Programming (Shin) 24

25 [ 註 例 ] Linux/C 에서메모리확보방법 Linux 메모리구성 system only 커널영역 stack 공유라이브러리가매핑된부분 %esp: stack pointer push/pop 명령에의해변경됨 run-time heap 초기화되지않은데이터 (.bss) 초기화된데이터 (.data) 실행프로그램코드 (.text) brk 포인터 heap 의최상위주소의다음주소를가리킴. heap memory 의크기는 brk() 와 sbrk() 함수에의해증가할수있음. 0 Spring 2010 System Programming (Shin) 25

26 동적인메모리할당 Dynamic memory allocation 관련작업 메모리할당 memory allocation 메모리할당요청에대하여주어진히프 (heap) 메모리에서블록단위로배정 메모리추가할당도가능 메모리해제 free 할당된메모리를할당가능한메모리로변경 해제의의무 : 프로그래머? 시스템? 시스템인경우 ( 묵시적할당 ) garbage collector 가할당공간을해제함 관련시스템콜 malloc(): 메모리할당 realloc(): 메모리추가할당 calloc(): 메모리할당후 0 으로초기화 brk(), sbrk(): heap 영역의확장 Spring 2010 System Programming (Shin) 26

27 [ 註 例 ] 동적인메모리할당 (1/3) malloc 관련시스템콜 #include <stdlib.h> void *malloc(size_t size) 메모리를히프영역에할당 성공시 ( 포인터타입으로 cast 했을때 ) 메모리블록을가리키는포인터를리턴 size 가 0 이면 NULL 을리턴 실패시 NULL 을리턴하고에러번호를설정 void *realloc(void *p, size_t size) 포인터 p 가가리키는블록의크기를 size 만큼변경하고 ( 만일블록의위치를바꾸면 ) 새로운블록에의포인터를리턴함 p 가바뀌더라도 p 가가리키던블록의내용은바뀌지않음 메모리공간이부족하면 NULL 을리턴하고에러번호를설정 void *calloc(size_t nmemb, size_t size) size nmemb 바이트의메모리를히프영역에할당 할당시, 내용값을 0 으로함 Spring 2010 System Programming (Shin) 27

28 [ 註 例 ] 동적인메모리할당 (2/3) malloc 관련시스템콜 ( 계속 ) #include <stdlib.h> void free(void *p) pointer p 가가리키는블록을할당가능하도록함 p 는 malloc/calloc/realloc 에의해설정된것임 int brk(void *end_data_segment) void *sbrk(ptrdiff_t increment) brk() 는데이터세그먼트의상단, 즉히프의상단을 end_data_segment 값으로설정. sbrk() 는히프의상단을 increment 바이트만큼증가시킴. sbrk() 는시스템콜이아니고 C library wrapper 임. brk() 는성공시 0 를, sbrk() 는성공시증가된영역의시작주소를리턴하고에러가발생하면 -1 을리턴 Spring 2010 System Programming (Shin) 28

29 [ 註 例 ] 동적인메모리할당 (3/3) malloc 사용예 getcwd() 현재프로세스자신이속해있는디렉토리의경로이름 (path name) 문자열을버퍼에저장. 버퍼크기가부족하면 ERANGE 란에러리턴. #include <stdlib.h> #include <unistd.h> #include <errno.h> #define INIT_BUFSIZE 1024 char* getcwd_new(void) { char *buf, *newbuf; size_t size = INIT_BUFSIZE; } buf = malloc(size); /* 디렉토리문자열저장용 */ if (!buf) return NULL; for (;;) { errno = 0; if (getcwd(buf, size)) return buf; /* 버퍼크기 OK */ if (errno!= ERANGE) break; size *= 2; /* 버퍼크기가작으면두배로 */ newbuf = realloc(buf, size); /* 버퍼를재할당 */ if (!newbuf) break; buf = newbuf; } free(buf); /* 할당된버퍼해제 */ return NULL; Spring 2010 System Programming (Shin) 29

30 동적메모리관리개념 동적인메모리할당 / 해제 allocation/deallocation 히프 (heap) 메모리안에서프로그램이요청하는메모리를할당및해제 문제점 : 할당과해제가반복되어, 할당된영역과할당되지않은영역을관리 ( 추적, 할당, 재할당, 인접영역의합병, 등 ) 하기어려움 목표 : 정확성 ( 오류없음 ), 효율성 ( 최대한가용공간활용 ), 성능 ( 할당속도 ) 보장 접근방법 메모리는바이트단위가아니라 ( 예를들면 ) 워드단위로할당 새로할당되는메모리영역은하나의 블록 으로관리 블록의시작주소는정렬됨. 예 ) 8-byte alignment 블록에대한정보 ( 할당여부, 인접블록에대한포인터, 블록의크기, 등 ): 블록에포함 자유 (free) 메모리 할당되지않은영역. 자유블록 (free block) 으로구성됨 메모리할당은자유메모리로부터가능함 메모리해제시자유메모리로합병됨 Spring 2010 System Programming (Shin) 30

31 [ 註 例 ] 동적메모리관리개념 (1/2) malloc() 에의한메모리할당예 b1 = malloc(6*sizeof(int)); b2 = malloc(3*sizeof(int)); b3 = malloc(5*sizeof(int)); b4 = malloc(2*sizeof(int)); free(b2) 할당됨 (allocated) 할당되지않음 (free) sizeof(int) word # block_1: 할당됨 (6 words) block_2: 할당안됨 (4 words) block_3 (5 words) block_4 (2 words) block_5 (6 words) 블록의구조 블록의앞에워드를추가하여블록의속성을표시할수있음 블록의속성 : 할당되었는지여부, 블록의크기등 자유블록의경우, 다음자유블록의주소를링크로서포함하여, 자유블록의 linked list 로서자유메모리를구성할수있음 (free list) Spring 2010 System Programming (Shin) 31

32 [ 註 例 ] 동적메모리관리개념 (2/2) malloc() 에의한메모리할당방법 free list word # allocated free not owned by malloc 블록의구조예 (pointer to next free block while free) size allocated space bp = malloc(n*sizeof(int)); size (n+2)*sizeof(int) bp header 블록의할당방법 malloc() 에의해메모리할당요청이있으면, free list 를스캔하여적절한크기의자유블록을찾아냄 요청한크기보다크면, 남는부분은 free list 에삽입 요청한크기의자유블록이없으면, OS 에메모리할당요청 free() 에의해메모리해제요청이있으면, free list 의적절한위치에해제된블록을삽입 만일기존의자유블록과인접해있는경우는서로합병함 Spring 2010 System Programming (Shin) 32

33 7.4 프로세스간통신 Interprocess Communication

34 기본적인프로세스간통신기법 데이터스트림과파이프 data stream and pipe 정보의송수신에사용되는일련의연속된데이터 a sequence of data used to send or receive information 예 : 프로세스와파일 ( 파일디스크립터을통하여 ) 을연결해주는데이터스트림 한쪽방향으로만가능함. 파일의경우입력, 출력의양방향연산을하므로쓰기 / 읽기각각의디스크립터를사용 파이프 : 프로세스사이를연결해주는데이터스트림 한프로세스의출력을다른프로세스의입력으로연결함 [Unix/Linux] 두종류의파이프 : (unnamed) pipe, named pipe unnamed pipe: 통상 pipe 라고부름 파일시스템에존재하지않고, 커널버퍼에의해데이터저장 - 인출 named pipe: FIFO(First In First Out) 라고부름 named pipe 는파일시스템에파일로서존재. 그러나실제디스크에는저장되지않고디렉토리에이름만존재하며, 파일의내용은주기억에저장됨. 파이프메커니즘에는 file position 이없음. 즉, lseek() 사용불가. 프로세스 1 파이프 프로세스 2 Spring 2010 System Programming (Shin) 34

35 파이프 pipe 파이프란? 프로세스사이를연결해주는데이터스트림 한프로세스의출력을다른프로세스의입력으로연결함 연결수단은읽기와쓰기파일디스크립터에의존함 데이터는커널의버퍼 (pipe buffer) 에저장되어전달되며, 외부에서접근할수없음. 두프로세스 (producer, consumer) 는파이프버퍼를사이에두고데이터에대한동기화가이루어짐. 즉, 한프로세스가버퍼에순차적으로데이터를써넣으면, 다른프로세스가차례로읽어감. 실제, 부모 ( 조상 )- 자식 ( 자손 ), 자식 - 자식프로세스사이의통신만가능 예 : Linux commands: prompt> ls l more 기호 은파이프를나타냄. ls 와 more 는 shell 의자식프로세스 파이프의제약점 하나의작업에서한방향으로만데이터전달가능 (half duplex) 즉, 읽고쓰기를섞어서할수없고, 한번읽기연산을하면그작업이끝날때까지읽기만가능함. 쓰기를하려면, 읽기가끝난후가능. 부모 - 자손, 조상이같은자손 - 자손프로세스사이에서만가능. 즉, file descriptor inheritance 가적용되는경우에만가능 예를들면, 디몬 (daemon) 과의데이터전달이불가능함 Spring 2010 System Programming (Shin) 35

36 pipe 관련시스템콜 #include <unistd.h> 파이프 int pipe(int fd[2]) 프로세스자신에주어지는파일디스크립터 (file descriptor, fd) 를설정함. 파일입출력과같은방법으로스트림을읽고씀. fd[0]: 읽기용, fd[1]: 쓰기용 read/write 는일반적인파일입출력을따름. 즉, ssize_t read(int fd, void *buf, size_t count) ssize_t write(int fd, const void *buf, size_t count) 한연산에서, 둘중하나만가능 file descriptor user process pipe(fd) fd[0] = 3 fd[1] = 4 pipe buffer ( 주기억에존재 ) kernel 어떤파일을접근하기위한추상적인키 (key). 이것이지정하는자료구조에의해다음정보를제공 : 파일에의포인터, 접근권리, 읽기 / 쓰기모드, 파일포지션, 등. fork 혹은 exec 에의해생성된자식프로세스는부모의 file descriptor 를물려받음. Spring 2010 System Programming (Shin) 36

37 [ 註 例 ] 파이프 파이프의사용방법 ( 예 ) 1. pipe() 호출 // fd[0](read), fd[1](write) 생성 2. fork() 호출 // 부모 (P), 자식 (C) 프로세스생성 3. 데이터전달 // 한방향으로만가능 half duplex (a) P sends to C: P 는 fd[0] 를닫고, fd[1] 에쓰기. C 는 fd[1] 을닫고, fd[0] 에서읽기 (b) C sends to P: C 는 fd[0] 를닫고, fd[1] 에쓰기. P 는 fd[1] 를닫고, fd[0] 에서읽기. full duplex pipe? 파이프는한작업에서한방향으로만데이터를전달할수있으므로 (half duplex), 만일양방향으로데이터를전달하려고하면 (full duplex) 미리두개의파이프를생성 ( 즉 pipe() 호출을두번수행 ) 하여, 각파이프를각방향으로지정함 pipe quiz (case 1) the producer does a close() on the pipe s write end, then can the consumer read any data buffered in the pipe? {Y} (case 2) the consumer does a close() on the pipe s read end, then can the producer write data to the write end? {N} Spring 2010 System Programming (Shin) 37

38 [ 註 例 ] 파이프 예제 : echo printing 이예에서는파이프하나를양방향으로사용하되, 부모가보내기작업이끝나면자식이보내기작업을시작함. 시나리오 1. 부모프로세스는표준입력으로부터입력된문자열을파이프를이용하여자식프로세스로보냄. 2. 자식프로세스는부모프로세스가보내온문자열을복사한다음, 다시파이프를이용하여부모프로세스에반송함 (echo) 3. 부모프로세스는자식에게서보내온문자열을표준출력으로출력함 부모프로세스 parent.c 다음쪽에계속 #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> int main() { char string_in[32], string_echo[32]; int fd[2], status; } if (pipe(fd) < 0) { exit(exit_failure); } fgets(string_in, sizeof(string_in), stdin); /* Step 1 */ if (fork() == 0) { if (execl("./child", "child", fd[0], fd[1], NULL) < 0) { exit(exit_failure); } } write(fd[1], &string_in, sizeof(string_in)); /* Step 1 */ wait(&status); read(fd[0], &string_echo, sizeof(string_echo)); /* Step 3 */ printf("echoed: %s\n", &string_echo); /* Step 3 */ close(fd[0]); close(fd[1]); return EXIT_SUCCESS; Spring 2010 System Programming (Shin) 38

39 #include <stdlib.h> #include <unistd.h> #include <string.h> int main(int argc, char *argv[]) { char str_in[32], str_echo[32]; int read_fd, write_fd; read_fd = atoi(argv[1]); write_fd = atoi(argv[2]); [ 註 例 ] 파이프 자식프로세스 child.c ( 실행파일 : child) /* Step 2: echo */ read(read_fd, &str_in, sizeof(str_in)); strncpy(str_echo, str_in, sizeof(str_echo)); write(write_fd, &str_echo, sizeof(str_echo)); } close(read_fd); close(write_fd); return EXIT_SUCCESS; stdin stdout 부모프로세스 parent pipe() fork() write() read() fd[0] fd[1] pipe buffer fd[0] fd[1] 자식프로세스 child echo Spring 2010 System Programming (Shin) 39

40 FIFOs (Named Pipes) FIFO 혹은 named pipe FIFO(First In First Out): unnamed pipe 의문제점을해결 일시적인버퍼를사용하지않고파일시스템에존재하는 persistent 객체를이용함 서로 ancestor-descendent 관계가없어도서로데이터를교환할수있음 named pipe(fifo) 의속성 named pipe 는파일시스템에파일로서존재. 그러나실제디스크에는저장되지않고디렉토리에이름만존재하며, 파일의내용은주기억에저장됨. 이파일은특수한파일로서한프로세스 (Pp, producer) 가이파일에데이터를차례로써넣으면, 다른프로세스 (Pc, consumer) 가써진순서대로읽어감. 일단읽으면, 데이터는지워짐. 즉, Pp 와 Pc 는동기화되어, Pp 는 Pc 가읽을때까지기다리고, Pc 는 Pp 가쓸때까지기다림. Spring 2010 System Programming (Shin) 40

41 FIFOs (Named Pipes) shell 에서의예 mkfifo [-m permission_mode] names default permission mode: $ mkfifo m 600 fifo1 $ cat <fifo1 wc l & {background 실행 } $ cat /etc/passwd >fifo1 위의예에서 cat <fifo1 에서아직 fifo1 이비어있으므로, 데이터가입력될때까지기다림 ( 동기화 ). producer-consumer 의예 : 위의예에서 cat <fifo1 wc l & 명령을두번입력하여실행하면 첫번째는 fifo1 가다찼을때수행되므로 passwd 파일의라인수가출력됨 두번째는첫번째실행에서 fifo1 의데이터가다소비되어, 빈파일이므로 0 이출력됨 system call int mkfifo(const char *pathname, mode_t mode); fifo special file 에대한 open/read/write 등은파일에대한일반적인명령을사용함 Spring 2010 System Programming (Shin) 41

42 [ 註 例 ] FIFOs (Named Pipes) 시나리오 rdfifo : 읽기를위한 fifo 를생성하여오픈한후, fifo 의출력을 stdout 에보임 wrfifo : 쓰기를위해 fifo 를오픈하고쓰기연산을수행 /* wrfifo.c - Write to a "well-known" FIFO */ int main(void) { int fd; /* Descriptor for FIFO */ int len; /* Bytes written to FIFO */ char buf[pipe_buf]; /* Ensure atomic writes */ time_t tp; /* For time call */ /* rdfifo.c - Create a FIFO and read from it */ int main(void) #include <sys/types.h> printf("i am %d\n", getpid()); /* Identify myself */ { #include <sys/stat.h> /* Open the FIFO write-only */ if((fd = open("fifo1", O_WRONLY)) < 0) { int fd; /* Descriptor for FIFO */ #include <unistd.h> perror("open"); int len; /* Bytes read from FIFO */ #include <errno.h> exit(exit_failure); char buf[pipe_buf]; #include <stdio.h> } mode_t mode = 0666; #include <stdlib.h> /* Generate some data to write */ if((mkfifo("fifo1", mode)) < 0) { #include <fcntl.h> while(1) { time(&tp); /* Get the current time */ perror("mkfifo"); #include <limits.h> /* Create the string to write */ exit(exit_failure); len = sprintf(buf, "wrfifo %d sends %s", } getpid(), ctime(&tp)); /* Open the FIFO read-only */ /* Use (len + 1) because sprintf does not count if((fd = open("fifo1", O_RDONLY)) < 0) { the terminating null */ perror("open"); if((write(fd, buf, len + 1)) < 0) { exit(exit_failure); perror("write"); } close(fd); /* Read and display the FIFO's output until EOF */ exit(exit_failure); while((len = read(fd, buf, PIPE_BUF - 1)) > 0) } printf("rdfifo read: %s", buf); sleep(3); close(fd); } close(fd); exit(exit_success); Source: Kurt Wall, Linux Programming by exit(exit_success); } Example, Que, 2000, pp } Spring 2010 System Programming (Shin) 42

43 시그널 signals 시그널 (signal) 이란? 사용자 ( 단말 ) 나커널이프로세스에연락하는방법 작은메시지로서, 시스템에서어떤이벤트가발생했음을프로세스에게알려줌 예외 (exception) 나인터럽트를커널레벨에서표현한것 (kernel abstraction) signal 에의해주어지는정보는단지 signal id( 정수 ) 와도착사실임 ID Name Default Action Corresponding Event 2 SIGINT Terminate ( 종료 ) Interrupt from keyboard (ctl-c) 9 SIGKILL Terminate Kill program (cannot override or ignore) 11 SIGSEGV Terminate & Dump Segmentation violation 14 SIGALRM Terminate Timer signal 17 SIGCHLD Ignore Child stopped or terminated Spring 2010 System Programming (Shin) 43

44 시그널 시그널의전송 커널이시그널을목적지프로세스 (destination process) 에보낸다는것은그프로세스의문맥에서어떤상태를갱신하는것 커널은다음의이유로시그널을보냄 커널이 divide-by-zero (SIGFPE) 혹은자식프로세스의종료 (SIGCHLD) 등의시스템이벤트를검출했을때 다른프로세스가목적지프로세스에시그널을보낼것을커널에명시적으로요청하기위해 kill system call 을호출했을때 시그널의수신 목적지프로세스가시그널을수신한다는것은커널이시그널을보낸데대해반응을보이는것임 다음과같이반응함 시그널을무시 (do nothing) 프로세스를종료 signal handler 라불리는사용자레벨의함수를실행함으로서 signal 을받음 (catch) - 인터럽트핸들러와유사함 프로세스의 core dump 를작성하고이상 ( 異常 ) 종료 Spring 2010 System Programming (Shin) 44

45 [ 註 例 ] 시그널 키보드에서시그널전송 ctrl-c (ctrl-z) 을키보드에서입력하면 SIGTERM (SIGTSTP) 를 foreground process group 에속하는모든작업에전송. SIGTERM 디폴트액션은각프로세스를종료하는것 SIGTSTP 디폴트액션은각프로세스를중단 (suspend) 하는것 사용예 : ctrl-c 와 ctrl-z linux> traceroute traceroute to moose.snu.ac.kr ( ) 30 hops max, 38 byte packets ( ) ( ) ms 3 * * * <typed ctrl-z> [1]+ Stopped traceroute linux> ps -l F S UID PID PPID TIME CMD 0 S :00:00 bash 4 T :00:00 traceroute 0 R :00:00 ps linux> fg traceroute 4 * * * <typed ctrl-c> linux> ps -l F S UID PID PPID TIME CMD 0 S :00:00 bash 0 R :00:00 ps Spring 2010 System Programming (Shin) 45

46 그밖의프로세스간통신기법 공유기억 ( 공유메모리 ) 를이용한프로세스간통신 여러개의프로세스가공통으로이용할수있는메모리공간제공 다수의프로세서가주기억 ( 메모리 ) 을공유하는경우, 멀티프로세서 (multiprocessors) 라부름 메시지를이용한프로세스간통신 메시지란일반적으로정보의집합체로서소스에서목적지로전달됨 두개의프로세스사이에서메시지를이용하여데이터송수신 이때프로세스는서로다른컴퓨터나프로세서에위치할수있음. 네트워크로연결된분산시스템에서원격프로세스간통신에이용될수있음 원격프로시져호출 (remote procedure calling) 네트워크로연결된원격컴퓨터의프로그램을호출 ( 실행 ) 하는메커니즘 메시지를이용하여요청 / 응답을송신 클라이언트 - 서버시스템에이용가능 Spring 2010 System Programming (Shin) 46

47 [ 註 例 ] 그밖의프로세스간통신기법 프로세스 프로세스 공유메모리 프로세스 프로세스 공유메모리를이용한통신 발신프로세스 메시지큐에저장 message queue 메시지큐에서인출 수신프로세스 메시지큐를이용한메시지통신 ( 단일컴퓨터시스템 ) Spring 2010 System Programming (Shin) 47

48 7.5 프로세스환경

49 환경변수 환경변수란? environment variables 부모프로세스에의해자식프로세스에전달되는변수로서프로세스의실행에관련된속성이나옵션을나타냄. 예를들면, 프로세스의부모. 자식관계를통하여전달되는전역변수 (global variable) 와같은것 환경변수에의액세스는전역변수 environ(type: char **) 을이용함 시스템콜 char *getenv(const char *name): 환경변수 name 의값검색 - 인출 int putenv(char *string): 환경변수의값을설정. name=value 의형식으로입력 Spring 2010 System Programming (Shin) 49

50 environ 의구조 [ 註 例 ] 환경변수 environ HOME EDITOR HOME=/home/system2 EDITOR=vi PAGER=less TERM=vt100 PWD=/usr/ LOGNAME=test NULL A user s login directory The user s preferred utility to edit text files 프로세스의모든 환경변수를출력 #include <stdio.h> #include <stdlib.h> extern char **environ; PAGER The user's preferred utility to display text files TERM The terminal type for which output is to be prepared PWD The current working directory LOGNAME The name of the logged-in user SHELL The file name of the user's login shell BROWSER The user's preferred utility to browse URLs int main(int argc, char *argv[]) { char **p; } for (p = environ; *p; p++) { printf("%s\n", *p); } exit(0); Spring 2010 System Programming (Shin) 50

51 시간관리 시간의표현 Unix time, Posix time Unix epoch(1970 년 1 월 1 일오전 0 시 ) 기준으로경과된초 ( 秒 ) 수산정 UTC (Coordinated universal time) 세계표준시간 local time, GMT time, etc. 시스템콜 #include <time.h> time_t time(time_t *tptr): Unix epoch 로부터현재까지의경과시간 ( 초 ) int gettimeofday(struct timeval *tv, struct timezone *tz): Unix epoch 로부터현재까지의경과시간 ( 초, 밀리초 ) struct tm *localtime(const time_t *timep): local time struct tm *gmttime(const time_t *timep): GMT time time_t mktime(struct tm *tm): local time UTC char *asctime(const struct tm *tm): calendar date/time char *ctime(const time_t *timep): calendar date/time, UTC Spring 2010 System Programming (Shin) 51

52 [ 註 例 ] 시간관리 커널 time() gettimeofday() struct timeval Unix epoch 로부터의경과시간, UTC struct tm { int tm_sec; /* seconds */ int tm_min; /* minutes */ int tm_hour; /* hours */ int tm_mday; /* day of the month */ int tm_mon; /* month */ int tm_year; /* year */ int tm_wday; /* day of the week */ int tm_yday; /* day in the year */ int tm_isdst; /* daylight saving time */ }; /* specified in <time.h> */ int time_t Unix epoch 로부터의경과초수, UTC ctime() 문자열 gmttime() localtime() mktime() struct tm 시간을 calendar time 으로유지, time zone (TZ) asctime() 문자열 struct timeval { time_t tv_sec; /* seconds */ suseconds_t tv_usec; /* microseconds */ }; /* specified in <sys/time.h> */ type time_t : represents calendar time When interpreted as an absolute time value it represents the number of seconds elapsed since Unix epoch. (specified in <sys/types.h>) Spring 2010 System Programming (Shin) 52

53 로그인과인증 로그인과정 1. init 프로세스가단말의수만큼 getty 명령을수행 (/etc/inittab 의설정에의거 ) getty 은 tty 포트를오픈하고 login 명령을수행하여로그인프롬프트를표시 2. getty 명령은단말로부터사용자의이름이입력되기를대기 3. login 명령이사용자를인증 4. 쉘 (shell) 을시작 init 단말수 fork 단말 file descriptor 0, 1, 2 getty login (shell) exec exec Spring 2010 System Programming (Shin) 53

54 [ 註 例 ] 로그인과인증 Shell programs shell 이란응용프로그램으로서사용자를대신해서프로그램을수행시킴 sh original Unix Bourne Shell csh BSD Unix C Shell tcsh Enhanced C Shell bash Bourne-Again Shell shell program 의수행은순차적으로 read/evaluate 스텝을계속하는것임 만일 shell 에서 foreground job 만을 reap 한다면 (cntl-c 등에의해 ), background job 을 reap 하기위해 signal 이란메커니즘이요구됨 (kill 명령에의해 ) int main() { char cmdline[maxline]; while (1) { /* read */ printf("> "); fgets(cmdline, MAXLINE, stdin); if (feof(stdin)) exit(0); } } /* evaluate */ eval(cmdline); Spring 2010 System Programming (Shin) 54

55 7.6 프로세스스케줄링

56 프로세스스케줄링 프로세스의상태 (states) 프로세스가 ready 상태나 waiting 상태일때는주어진큐에서다음상태가될때까지기다림 시작 (initiated) 준비완료 (ready) 디스팻치 입출력완료 타이머인터럽트 ( 일시중지 ) 대기중 (waiting) 입출력요구 ( 일시중지 ) 실행중 (running) 종료 (terminated) Spring 2010 System Programming (Shin) 56

57 프로세스스케줄링 스케쥴링 scheduling 여러개의프로세스가실행되려고할때순번을정함 ( 아래의디스팻칭개념을포함할수도있음 ) 디스팻칭 dispatching 실행되도록스케쥴된프로세스를 CPU 상에서실행시킴 스케줄링의목표 컴퓨터시스템의계산목표에따름. 예를들면, 실시간시스템 : 응답시간 (response time) 뱃치 (batch) 처리시스템 : 처리율혹은처리량 (throughput) 시분할시스템 (timesharing system): 프로세서의효율성, 응답시간 스케줄러의설계목표 프로세스간 CPU 시간을공평하게공유 프로세서를효율적으로이용 스케줄링오버헤드가낮음 프로세스의중요도나긴급도에따른우선순위의설정 어떤프로세스도영원히스케줄링에서제외되면안됨 (no starvation) Spring 2010 System Programming (Shin) 57

58 [ 註 例 ] 프로세스스케줄링 새프로세스 Ready queue CPU 계산을종료한프로세스 일시중지 (timer interrupt, I/O request) I/O I/O queue I/O request Time slice expired Child terminates Child executes Fork a child 프로세스스케쥴링 Interrupt occurs Wait for an interrupt CPU 에서수행중이러한일이발생하면프로세스는해당일을마친후다시 ready queue 에들어간다. Spring 2010 System Programming (Shin) 58

59 스케줄링할때고려사항 우선순위 priorities 프로세스의계산작업의긴급성혹은중요성등에의해결정 우선순위가높은것을우선적으로 CPU 에스케줄링 통상각각의우선순위마다별개의스케줄큐를만듦 예 ) 휴대전화운영체제의스케줄러에서 전화통화, 문자서비스 (SMS), 일정관리 순으로우선순위를설정 다음에수행될프로세스의선정방법 예 : 다음의값이가장높은프로세스를선정 : p = f(w, e, s), 단, 스케줄링시스템에도착한후경과시간 (w) 현재까지 CPU 에서수행된시간 (e) 해당프로세스가요구하는총실행시간 (s) 스케줄시점에서의프로세스교체여부의결정방법 선점 (preemptive): 우선순위높은프로세스가낮은프로세스를교체함 비선점 (nonpreemptive): 우선순위가높더라도현재 CPU 에서수행중인 [ 낮은우선순위의 ] 프로세스가종료될때까지기다림 Spring 2010 System Programming (Shin) 59

60 Priority queuing [ 註 例 ] 스케줄링할때고려사항 Source: W. Stallings, Operating Systems, 6e, 2008, Chapter 9 Spring 2010 System Programming (Shin) 60

61 문맥교환 프로세스의교체 ( 문맥교환 ) process switching, context switching 문맥교환에의해제어권이한프로세스에서다른프로세스로넘어감 발생시기 round robin 스케줄링에서시간슬라이스종료시 입출력요청시 인터럽트처리시 조치 현재실행중인프로세스의실행환경 ( 상태 ) 을저장 프로세스상태 (process state) memory image + register values + program counter 다음실행할프로세스를선정한후디스팻칭 Spring 2010 System Programming (Shin) 61

62 [ 註 例 ] 문맥교환 Process A code Process B code 시간 user code (A) kernel code user code (B) kernel code user code (A) context switch context switch Spring 2010 System Programming (Shin) 62

63 스케줄링정책 스케쥴링정책 ( 예 ) scheduling policies shortest job first, shortest process next 가장실행시간이짧은작업을우선실행 실행시간을미리결정가능하거나예측가능하여야함 round robin 모든프로세스가일정시간만큼의실행시간 (time slice) 을배당받음. 준비상태인프로세스가차례로실행됨 할당된시간종료시선점 (preemption) 됨 프로세스의교체 시분할시스템에적합 FCFS 스케줄큐에도착한순서대로스케줄링 오버헤드가가장낮음 수행시간이짧은프로세스에불리함 프로세스스케줄링예제 프로세스 도착시간 총실행시간 A 0 3 B 2 6 C 4 4 D 6 5 E 8 2 Spring 2010 System Programming (Shin) 63

64 [ 註 例 ] 스케줄링정책 Source: W. Stallings, Operating Systems, 6e, 2008, Chapter 9 Spring 2010 System Programming (Shin) 64

슬라이드 1

슬라이드 1 7.4 프로세스간통신 Interprocess Communication 기본적인프로세스간통신기법 데이터스트림과파이프 data stream and pipe 정보의송수신에사용되는일련의연속된데이터 a sequence of data used to send or receive information 예 : 프로세스와파일 ( 파일디스크립터을통하여 ) 을연결해주는데이터스트림

More information

6주차.key

6주차.key 6, Process concept A program in execution Program code PCB (process control block) Program counter, registers, etc. Stack Heap Data section => global variable Process in memory Process state New Running

More information

슬라이드 1

슬라이드 1 / 유닉스시스템개요 / 파일 / 프로세스 01 File Descriptor file file descriptor file type unix 에서의파일은단지바이트들의나열임 operating system 은파일에어떤포맷도부과하지않음 파일의내용은바이트단위로주소를줄수있음 file descriptor 는 0 이나양수임 file 은 open 이나 creat 로 file

More information

제1장 Unix란 무엇인가?

제1장  Unix란 무엇인가? 1 12 장파이프 2 12.1 파이프 파이프원리 $ who sort 파이프 3 물을보내는수도파이프와비슷 한프로세스는쓰기용파일디스크립터를이용하여파이프에데이터를보내고 ( 쓰고 ) 다른프로세스는읽기용파일디스크립터를이용하여그파이프에서데이터를받는다 ( 읽는다 ). 한방향 (one way) 통신 파이프생성 파이프는두개의파일디스크립터를갖는다. 하나는쓰기용이고다른하나는읽기용이다.

More information

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

Microsoft PowerPoint - ch09_파이프 [호환 모드] 학습목표 파이프를이용한 IPC 기법을이해한다. 이름없는파이프를이용해통신프로그램을작성할수있다. 이름있는파이프를이용해통신프로그램을작성할수있다. 파이프 IT CookBook, 유닉스시스템프로그래밍 2/20 목차 파이프의개념 이름없는파이프만들기 복잡한파이프생성 양방향파이프활용 이름있는파이프만들기 파이프의개념 파이프 두프로세스간에통신할수있도록해주는특수파일 그냥파이프라고하면일반적으로이름없는파이프를의미

More information

2009년 상반기 사업계획

2009년 상반기 사업계획 파이프 IT CookBook, 유닉스시스템프로그래밍 학습목표 파이프를이용한 IPC 기법을이해한다. 이름없는파이프를이용해통신프로그램을작성할수있다. 이름있는파이프를이용해통신프로그램을작성할수있다. 2/20 목차 파이프의개념 이름없는파이프만들기 복잡한파이프생성 양방향파이프활용 이름있는파이프만들기 3/20 파이프의개념 파이프 두프로세스간에통신할수있도록해주는특수파일 그냥파이프라고하면일반적으로이름없는파이프를의미

More information

슬라이드 1

슬라이드 1 -Part3- 제 4 장동적메모리할당과가변인 자 학습목차 4.1 동적메모리할당 4.1 동적메모리할당 4.1 동적메모리할당 배울내용 1 프로세스의메모리공간 2 동적메모리할당의필요성 4.1 동적메모리할당 (1/6) 프로세스의메모리구조 코드영역 : 프로그램실행코드, 함수들이저장되는영역 스택영역 : 매개변수, 지역변수, 중괄호 ( 블록 ) 내부에정의된변수들이저장되는영역

More information

ABC 11장

ABC 11장 12 장고급응용 0 수행중인프로그램 프로세스 모든프로세스는유일한프로세스식별번호 (PID) 를가짐 유닉스에서는 ps 명령을사용하여프로세스목록을볼수있음 12-1 프로세스 $ ps -aux USER PID %CPU %MEM SZ RSS TT STAT START TIME COMMAND blufox 17725 34.0 1.6 146 105 i2 R 15:13 0:00

More information

10.

10. 10. 10.1 10.2 Library Routine: void perror (char* str) perror( ) str Error 0 10.3 10.3 int fd; /* */ fd = open (filename, ) /*, */ if (fd = = -1) { /* */ } fcnt1 (fd, ); /* */ read (fd, ); /* */ write

More information

제1장 Unix란 무엇인가?

제1장  Unix란 무엇인가? 4 장파일 컴퓨터과학과박환수 1 2 4.1 시스템호출 컴퓨터시스템구조 유닉스커널 (kernel) 하드웨어를운영관리하여다음과같은서비스를제공 파일관리 (File management) 프로세스관리 (Process management) 메모리관리 (Memory management) 통신관리 (Communication management) 주변장치관리 (Device

More information

11장 포인터

11장 포인터 Dynamic Memory and Linked List 1 동적할당메모리의개념 프로그램이메모리를할당받는방법 정적 (static) 동적 (dynamic) 정적메모리할당 프로그램이시작되기전에미리정해진크기의메모리를할당받는것 메모리의크기는프로그램이시작하기전에결정 int i, j; int buffer[80]; char name[] = data structure"; 처음에결정된크기보다더큰입력이들어온다면처리하지못함

More information

좀비프로세스 2

좀비프로세스 2 Signal & Inter-Process Communication Department of Computer Engineering Kyung Hee University. Choong Seon Hong 1 좀비프로세스 2 좀비프로세스 (zombie process) 좀비프로세스란프로세스종료후메모리상에서사라지지않는프로세스 좀비프로세스의생성이유. 자식프로세스는부모프로세스에게실행결과에대한값을반환해야한다.

More information

Microsoft PowerPoint - chap9 [호환 모드]

Microsoft PowerPoint - chap9 [호환 모드] 제 9 장프로세스관계 숙대창병모 1 Contents 1. Logins 2. Process Groups 3. Sessions 4. Controlling Terminal 5. Job Control 숙대창병모 2 로그인 숙대창병모 3 터미널로그인 /etc/ttys: 1 line per terminal device getty: opens terminal device

More information

제9장 프로세스 제어

제9장 프로세스 제어 제 9 장프로세스제어 리눅스시스템프로그래밍 청주대학교전자공학과 한철수 제 9 장 목차 프로세스생성 프로그램실행 입출력재지정 프로세스그룹 시스템부팅 2 9.1 절 프로세스생성 fork() 시스템호출 새로운프로그램을실행하기위해서는먼저새로운프로세스를생성해야하는데, fork() 시스템호출이새로운프로세스를생성하는유일한방법임. 함수프로토타입 pid_t fork(void);

More information

/chroot/lib/ /chroot/etc/

/chroot/lib/ /chroot/etc/ 구축 환경 VirtualBox - Fedora 15 (kernel : 2.6.40.4-5.fc15.i686.PAE) 작동 원리 chroot유저 ssh 접속 -> 접속유저의 홈디렉토리 밑.ssh의 rc 파일 실행 -> daemonstart실행 -> daemon 작동 -> 접속 유저만의 Jail 디렉토리 생성 -> 접속 유저의.bashrc 의 chroot 명령어

More information

Microsoft PowerPoint - 09-Pipe

Microsoft PowerPoint - 09-Pipe 9. 파이프 상명대학교소프트웨어학부 파이프 시그널은이상한사건이나오류를처리하는데는이용하지만, 한프로세스로부터다른프로세스로대량의정보를전송하는데는부적합하다. 파이프 한프로세스를다른관련된프로세스에연결시켜주는단방향의통신채널 2 pipe() Usage #include int pipe(int filedes[2]); 3 < ex_1.c > #include

More information

제12장 파일 입출력

제12장 파일 입출력 제 4 장파일입출력 리눅스시스템프로그래밍 청주대학교전자공학과 한철수 1 시스템호출 (system call) 파일 (file) 임의접근 (random access) 주요학습내용 2 4.1 절 커널의역할 (kernel) 커널 (kernel) 은운영체제의핵심부분으로서, 하드웨어를운영관리하는여러가지서비스를제공함 파일관리 (File management) 디스크 프로세스관리

More information

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

1장.  유닉스 시스템 프로그래밍 개요 Unix 프로그래밍및실습 7 장. 시그널 - 과제보충 응용과제 1 부모프로세스는반복해서메뉴를출력하고사용자로부터주문을받아자식프로세스에게주문내용을알린다. (SIGUSR1) ( 일단주문을받으면음식이완료되기전까지 SIGUSR1 을제외한다른시그널은모두무시 ) timer 자식프로세스는주문을받으면조리를시작한다. ( 일단조리를시작하면음식이완성되기전까지 SIGALARM 을제외한다른시그널은모두무시

More information

이번장에서학습할내용 동적메모리란? malloc() 와 calloc() 연결리스트 파일을이용하면보다많은데이터를유용하고지속적으로사용및관리할수있습니다. 2

이번장에서학습할내용 동적메모리란? malloc() 와 calloc() 연결리스트 파일을이용하면보다많은데이터를유용하고지속적으로사용및관리할수있습니다. 2 제 17 장동적메모리와연결리스트 유준범 (JUNBEOM YOO) Ver. 2.0 jbyoo@konkuk.ac.kr http://dslab.konkuk.ac.kr 본강의자료는생능출판사의 PPT 강의자료 를기반으로제작되었습니다. 이번장에서학습할내용 동적메모리란? malloc() 와 calloc() 연결리스트 파일을이용하면보다많은데이터를유용하고지속적으로사용및관리할수있습니다.

More information

61 62 63 64 234 235 p r i n t f ( % 5 d :, i+1); g e t s ( s t u d e n t _ n a m e [ i ] ) ; if (student_name[i][0] == \ 0 ) i = MAX; p r i n t f (\ n :\ n ); 6 1 for (i = 0; student_name[i][0]!= \ 0&&

More information

Microsoft PowerPoint - o8.pptx

Microsoft PowerPoint - o8.pptx 메모리보호 (Memory Protection) 메모리보호를위해 page table entry에 protection bit와 valid bit 추가 Protection bits read-write / read-only / executable-only 정의 page 단위의 memory protection 제공 Valid bit (or valid-invalid bit)

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 KeyPad Device Control - Device driver Jo, Heeseung HBE-SM5-S4210 에는 16 개의 Tack Switch 를사용하여 4 행 4 열의 Keypad 가장착 4x4 Keypad 2 KeyPad 를제어하기위하여 FPGA 내부에 KeyPad controller 가구현 KeyPad controller 16bit 로구성된

More information

Microsoft PowerPoint - Lecture_Note_7.ppt [Compatibility Mode]

Microsoft PowerPoint - Lecture_Note_7.ppt [Compatibility Mode] Unix Process Department of Computer Engineering Kyung Hee University. Choong Seon Hong 1 유닉스기반다중서버구현방법 클라이언트들이동시에접속할수있는서버 서비스를동시에처리할수있는서버프로세스생성을통한멀티태스킹 (Multitasking) 서버의구현 select 함수에의한멀티플렉싱 (Multiplexing)

More information

<4D F736F F F696E74202D20B8AEB4AABDBA20BFC0B7F920C3B3B8AEC7CFB1E22E BC8A3C8AF20B8F0B5E55D>

<4D F736F F F696E74202D20B8AEB4AABDBA20BFC0B7F920C3B3B8AEC7CFB1E22E BC8A3C8AF20B8F0B5E55D> 리눅스 오류처리하기 2007. 11. 28 안효창 라이브러리함수의오류번호얻기 errno 변수기능오류번호를저장한다. 기본형 extern int errno; 헤더파일 라이브러리함수호출에실패했을때함수예 정수값을반환하는함수 -1 반환 open 함수 포인터를반환하는함수 NULL 반환 fopen 함수 2 유닉스 / 리눅스 라이브러리함수의오류번호얻기 19-1

More information

<4D F736F F F696E74202D FB8DEB8F0B8AE20B8C5C7CE205BC8A3C8AF20B8F0B5E55D>

<4D F736F F F696E74202D FB8DEB8F0B8AE20B8C5C7CE205BC8A3C8AF20B8F0B5E55D> 학습목표 통신프로그램이무엇인지이해한다. 을이용한 IPC 기법을이해한다. 함수를사용해프로그램을작성할수있다. IT CookBook, 유닉스시스템프로그래밍 2/20 목차 의개념 함수 해제함수 의보호모드변경 파일의크기확장 매핑된메모리동기화 데이터교환하기 의개념 파일을프로세스의메모리에매핑 프로세스에전달할데이터를저장한파일을직접프로세스의가상주소공간으로매핑 read, write

More information

강의10

강의10 Computer Programming gdb and awk 12 th Lecture 김현철컴퓨터공학부서울대학교 순서 C Compiler and Linker 보충 Static vs Shared Libraries ( 계속 ) gdb awk Q&A Shared vs Static Libraries ( 계속 ) Advantage of Using Libraries Reduced

More information

chap7.key

chap7.key 1 7 C 2 7.1 C (System Calls) Unix UNIX man Section 2 C. C (Library Functions) C 1975 Dennis Ritchie ANSI C Standard Library 3 (system call). 4 C?... 5 C (text file), C. (binary file). 6 C 1. : fopen( )

More information

Chap04(Signals and Sessions).PDF

Chap04(Signals and Sessions).PDF Signals and Session Management 2002 2 Hyun-Ju Park (Signal)? Introduction (1) mechanism events : asynchronous events - interrupt signal from users : synchronous events - exceptions (accessing an illegal

More information

untitled

untitled Step Motor Device Driver Embedded System Lab. II Step Motor Step Motor Step Motor source Embedded System Lab. II 2 open loop, : : Pulse, 1 Pulse,, -, 1 +5%, step Step Motor (2),, Embedded System Lab. II

More information

Chapter #01 Subject

Chapter #01  Subject Device Driver March 24, 2004 Kim, ki-hyeon 목차 1. 인터럽트처리복습 1. 인터럽트복습 입력검출방법 인터럽트방식, 폴링 (polling) 방식 인터럽트서비스등록함수 ( 커널에등록 ) int request_irq(unsigned int irq, void(*handler)(int,void*,struct pt_regs*), unsigned

More information

2009년 상반기 사업계획

2009년 상반기 사업계획 메모리매핑 IT CookBook, 유닉스시스템프로그래밍 학습목표 통신프로그램이무엇인지이해한다. 메모리매핑을이용한 IPC 기법을이해한다. 메모리매핑함수를사용해프로그램을작성할수있다. 2/20 목차 메모리매핑의개념 메모리매핑함수 메모리매핑해제함수 메모리매핑의보호모드변경 파일의크기확장 매핑된메모리동기화 데이터교환하기 3/20 메모리매핑의개념 메모리매핑 파일을프로세스의메모리에매핑

More information

2009년 상반기 사업계획

2009년 상반기 사업계획 소켓프로그래밍활용 IT CookBook, 유닉스시스템프로그래밍 학습목표 소켓인터페이스를활용한다양한프로그램을작성할수있다. 2/23 목차 TCP 기반프로그래밍 반복서버 동시동작서버 동시동작서버-exec함수사용하기 동시동작서버-명령행인자로소켓기술자전달하기 UDP 프로그래밍 3/23 TCP 기반프로그래밍 반복서버 데몬프로세스가직접모든클라이언트의요청을차례로처리 동시동작서버

More information

리눅스 프로세스 관리

리눅스 프로세스 관리 프로세스 (Process) Process 프로그램이나명령어를실행하면메모리에적재되어실제로실행되고있는상태를의미 이러한프로세스들은프로세스가시작하면서할당받는프로세스식별번호인 PID(Process ID), 해당프로세스를실행한부모프로세스를나타내는 PPID(Parent Process ID), UID 와 GID 정보를통해해당프로세스가어느사용자에속해있는지, 프로세스가파일에대해갖는권한및프로세스가실행된터미널,

More information

<4D F736F F F696E74202D FC7C1B7CEBCBCBDBA20BBFDBCBAB0FA20BDC7C7E0205BC8A3C8AF20B8F0B5E55D>

<4D F736F F F696E74202D FC7C1B7CEBCBCBDBA20BBFDBCBAB0FA20BDC7C7E0205BC8A3C8AF20B8F0B5E55D> 학습목표 프로세스를생성하는방법을이해한다. 프로세스를종료하는방법을이해한다. exec함수군으로새로운프로그램을실행하는방법을이해한다. 프로세스를동기화하는방법을이해한다. 프로세스생성과실행 IT CookBook, 유닉스시스템프로그래밍 2/24 목차 프로세스생성 프로세스종료함수 exec 함수군활용 exec 함수군과 fork 함수 프로세스동기화 프로세스생성 [1] 프로그램실행

More information

2009년 상반기 사업계획

2009년 상반기 사업계획 프로세스생성과실행 IT CookBook, 유닉스시스템프로그래밍 학습목표 프로세스를생성하는방법을이해한다. 프로세스를종료하는방법을이해한다. exec함수군으로새로운프로그램을실행하는방법을이해한다. 프로세스를동기화하는방법을이해한다. 2/24 목차 프로세스생성 프로세스종료함수 exec 함수군활용 exec 함수군과 fork 함수 프로세스동기화 3/24 프로세스생성 [1]

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 UNIX 및실습 8 장. 프로세스와사용자 명령익히기 1 학습목표 유닉스에서프로세스가무엇인지그개념을이해한다. 프로세스와관련된유닉스명령의사용방법을익힌다. 포그라운드처리와백그라운드처리의차이를이해한다. 사용자정보를보는명령의사용방법을익힌다. 2 01. 프로세스의개념과종류 프로세스 (process) 현재시스템에서실행중인프로그램 프로세스는고유번호를가진다. Process

More information

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

Microsoft PowerPoint - chap13-입출력라이브러리.pptx #include int main(void) int num; printf( Please enter an integer: "); scanf("%d", &num); if ( num < 0 ) printf("is negative.\n"); printf("num = %d\n", num); return 0; 1 학습목표 스트림의 기본 개념을 알아보고,

More information

슬라이드 1

슬라이드 1 Task 통신및동기화 : 파이프 (Pipe) Chapter #11 파이프 (Unamed Pipe) 표준입출력과파이프 FIFO(Named Pipe) 강의목차 Unix System Programming 2 파이프 (Unnamed Pipe) 파이프 (Pipe) (1) 하나의프로세스를다른프로세스에연결시켜주는단방향의통신채널 입출력채널과동기화기능을제공하는특수한형태의파일

More information

Microsoft PowerPoint - chap6 [호환 모드]

Microsoft PowerPoint - chap6 [호환 모드] 제 6 장프로세스 (Process) 숙대창병모 1 내용 프로세스시작 / 종료 명령중인수 / 환경변수 메모리배치 / 할당 비지역점프 숙대창병모 2 프로세스시작 / 종료 숙대창병모 3 Process Start Kernel exec system call user process Cstart-up routine call return int main(int argc,

More information

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

임베디드시스템설계강의자료 6 system call 2/2 (2014 년도 1 학기 ) 김영진 아주대학교전자공학과 임베디드시스템설계강의자료 6 system call 2/2 (2014 년도 1 학기 ) 김영진 아주대학교전자공학과 System call table and linkage v Ref. http://www.ibm.com/developerworks/linux/library/l-system-calls/ - 2 - Young-Jin Kim SYSCALL_DEFINE 함수

More information

Chap06(Interprocess Communication).PDF

Chap06(Interprocess Communication).PDF Interprocess Communication 2002 2 Hyun-Ju Park Introduction (interprocess communication; IPC) IPC data transfer sharing data event notification resource sharing process control Interprocess Communication

More information

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

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 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 Example 3.1 Files 3.2 Source code 3.3 Exploit flow

More information

Sena Technologies, Inc. HelloDevice Super 1.1.0

Sena Technologies, Inc. HelloDevice Super 1.1.0 HelloDevice Super 110 Copyright 1998-2005, All rights reserved HelloDevice 210 ()137-130 Tel: (02) 573-5422 Fax: (02) 573-7710 E-Mail: support@senacom Website: http://wwwsenacom Revision history Revision

More information

Microsoft PowerPoint - [2009] 02.pptx

Microsoft PowerPoint - [2009] 02.pptx 원시데이터유형과연산 원시데이터유형과연산 원시데이터유형과연산 숫자데이터유형 - 숫자데이터유형 원시데이터유형과연산 표준입출력함수 - printf 문 가장기본적인출력함수. (stdio.h) 문법 ) printf( Test printf. a = %d \n, a); printf( %d, %f, %c \n, a, b, c); #include #include

More information

Microsoft PowerPoint - 10_Process

Microsoft PowerPoint - 10_Process Linux 프로세스프로그래밍 Programming - 프로세스생성 : fork, exec - 프로세스동기화 : wait - 프로세스관리함수 프로세스관련함수 프로세스생성과종료 함수 의미 fork 자신과완전히동일한프로세스를생성한다. exec 계열지정한실행파일로부터프로세스를생성한다. exit 종료에따른상태값을부모프로세스에게전달하며프로세스를종료한다. atexit exit

More information

Microsoft PowerPoint APUE(File InO).pptx

Microsoft PowerPoint APUE(File InO).pptx Linux/UNIX Programming 문양세강원대학교 IT대학컴퓨터과학전공 강의목표및내용 강의목표 파일의특성을이해한다. 파일을열고닫는다. 파일로부터데이터를읽고쓴다. 기타파일제어함수를익힌다. 강의내용 파일구조 (UNIX 파일은어떤구조일까?) 파일관련시스템호출 시스템호출의효율과구조 Page 2 What is a File? A file is a contiguous

More information

System Programming Lab

System Programming Lab System Programming Lab Week 4: Shell Schedule for your own shell 1 st shell 기본기능 fork / exec Background Processing/ Sequential Execution ls, find, grep 2 nd Environment variables/ Shell variables built-in

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 System Software Experiment 1 Lecture 5 - Array Spring 2019 Hwansoo Han (hhan@skku.edu) Advanced Research on Compilers and Systems, ARCS LAB Sungkyunkwan University http://arcs.skku.edu/ 1 배열 (Array) 동일한타입의데이터가여러개저장되어있는저장장소

More information

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

Microsoft PowerPoint - chap02-C프로그램시작하기.pptx #include int main(void) { int num; printf( Please enter an integer "); scanf("%d", &num); if ( num < 0 ) printf("is negative.\n"); printf("num = %d\n", num); return 0; } 1 학습목표 을 작성하면서 C 프로그램의

More information

Microsoft PowerPoint APUE(Intro).ppt

Microsoft PowerPoint APUE(Intro).ppt 컴퓨터특강 () [Ch. 1 & Ch. 2] 2006 년봄학기 문양세강원대학교컴퓨터과학과 APUE 강의목적 UNIX 시스템프로그래밍 file, process, signal, network programming UNIX 시스템의체계적이해 시스템프로그래밍능력향상 Page 2 1 APUE 강의동기 UNIX 는인기있는운영체제 서버시스템 ( 웹서버, 데이터베이스서버

More information

슬라이드 1

슬라이드 1 프로세스 (Process) (1) Chapter #5 Process 정의 Process 구조 Process Context Process Scheduling 강의목차 Unix System Programming 2 Program( 프로그램 ) Process 정의 (1) 기계어명령어와데이터를모아놓은실행파일 C 언어등프로그램언어로작성된소스파일을컴파일링하여생성 COFF(Common

More information

Microsoft PowerPoint - chap2

Microsoft PowerPoint - chap2 제 2 장. 파일입출력 (File I/O) 숙대창병모 1 목표 파일의구조및특성을이해한다. 파일을열고닫는다. 파일로부터데이터를읽고쓴다. 파일현재위치변경 기타파일제어 숙대창병모 2 2.1 파일구조 숙대창병모 3 What is a file? a file is a contiguous sequence of bytes no format imposed by the operating

More information

The Pocket Guide to TCP/IP Sockets: C Version

The Pocket Guide to  TCP/IP Sockets: C Version 인터넷프로토콜 5 장 데이터송수신 (3) 1 파일전송메시지구성예제 ( 고정크기메시지 ) 전송방식 : 고정크기 ( 바이너리전송 ) 필요한전송정보 파일이름 ( 최대 255 자 => 255byte 의메모리공간필요 ) 파일크기 (4byte 의경우최대 4GB 크기의파일처리가능 ) 파일내용 ( 가변길이, 0~4GB 크기 ) 메시지구성 FileName (255bytes)

More information

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

1장.  유닉스 시스템 프로그래밍 개요 9 장. 파이프 Unix 프로그래밍및실습 1 강의내용 1 절개요 2 절이름없는파이프 3 절이름있는파이프 http://lily.mmu.ac.kr/lecture/13u2/ch09.pdf 책에나온내용반드시 man 으로확인할것! UNIX, LINUX 등시스템마다차이가있을수있음을반드시인식 2 기본실습 #1 [ 예제 9-1] ~ [ 예제 9-7] ( 각 10점 ) 과제개요

More information

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

Microsoft PowerPoint - chap10-함수의활용.pptx #include int main(void) { int num; printf( Please enter an integer: "); scanf("%d", &num); if ( num < 0 ) printf("is negative.\n"); printf("num = %d\n", num); return 0; } 1 학습목표 중 값에 의한 전달 방법과

More information

untitled

untitled Embedded System Lab. II Embedded System Lab. II 2 RTOS Hard Real-Time vs Soft Real-Time RTOS Real-Time, Real-Time RTOS General purpose system OS H/W RTOS H/W task Hard Real-Time Real-Time System, Hard

More information

UniStore

UniStore Chapter 3. Process Concept Introduction to Operating Systems CSW3020 Prof. Young Pyo JUN CSW3020/Introduction to Operating Systems 1 What is a Process? 실행중인프로그램 프로그램은저장장치에, 프로세스는메인메모리에존재 시스템콜을통해자원을요구하는개체

More information

BMP 파일 처리

BMP 파일 처리 BMP 파일처리 김성영교수 금오공과대학교 컴퓨터공학과 학습내용 영상반전프로그램제작 2 Inverting images out = 255 - in 3 /* 이프로그램은 8bit gray-scale 영상을입력으로사용하여반전한후동일포맷의영상으로저장한다. */ #include #include #define WIDTHBYTES(bytes)

More information

Figure 5.01

Figure 5.01 Chapter 4: Threads Yoon-Joong Kim Hanbat National University, Computer Engineering Department Chapter 4: Multithreaded Programming Overview Multithreading Models Thread Libraries Threading Issues Operating

More information

<4D F736F F F696E74202D20C1A63137C0E520B5BFC0FBB8DEB8F0B8AEBFCD20BFACB0E1B8AEBDBAC6AE>

<4D F736F F F696E74202D20C1A63137C0E520B5BFC0FBB8DEB8F0B8AEBFCD20BFACB0E1B8AEBDBAC6AE> 쉽게풀어쓴 C 언어 Express 제 17 장동적메모리와연결리스트 이번장에서학습할내용 동적메모리할당의이해 동적메모리할당관련함수 연결리스트 동적메모리할당에대한개념을이해하고응용으로연결리스트를학습합니다. 동적할당메모리의개념 프로그램이메모리를할당받는방법 정적 (static) 동적 (dynamic) 정적메모리할당 정적메모리할당 프로그램이시작되기전에미리정해진크기의메모리를할당받는것

More information

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

A Dynamic Grid Services Deployment Mechanism for On-Demand Resource Provisioning C Programming Practice (II) Contents 배열 문자와문자열 구조체 포인터와메모리관리 구조체 2/17 배열 (Array) (1/2) 배열 동일한자료형을가지고있으며같은이름으로참조되는변수들의집합 배열의크기는반드시상수이어야한다. type var_name[size]; 예 ) int myarray[5] 배열의원소는원소의번호를 0 부터시작하는색인을사용

More information

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

임베디드시스템설계강의자료 6 system call 1/2 (2014 년도 1 학기 ) 김영진 아주대학교전자공학과 임베디드시스템설계강의자료 6 system call 1/2 (2014 년도 1 학기 ) 김영진 아주대학교전자공학과 시스템호출개요 리눅스에서는사용자공간과커널공간을구분 사용자프로그램은사용자모드, 운영체제는커널모드에서수행 커널공간에대한접근은커널 ( 특권, priviledged) 모드에서가능 컴퓨팅자원 (CPU, memory, I/O 등 ) 을안전하게보호 커널수행을안전하게유지

More information

SRC PLUS 제어기 MANUAL

SRC PLUS 제어기 MANUAL ,,,, DE FIN E I N T R E A L L O C E N D SU B E N D S U B M O TIO

More information

Microsoft PowerPoint APUE(File InO)

Microsoft PowerPoint APUE(File InO) Linux/UNIX Programming 문양세강원대학교 IT특성화대학컴퓨터과학전공 강의목표및내용 강의목표 파일의특성을이해한다. 파일을열고닫는다. 파일로부터데이터를읽고쓴다. 기타파일제어함수를익힌다. 강의내용 파일구조 (UNIX 파일은어떤구조일까?) 파일관련시스템호출 시스템호출의효율과구조 Page 2 What is a File? A file is a contiguous

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 7-Segment Device Control - Device driver Jo, Heeseung HBE-SM5-S4210 의 M3 Module 에는 6 자리를가지는 7-Segment 모듈이아래그림처럼실장 6 Digit 7-Segment 2 6-Digit 7-Segment LED controller 16비트로구성된 2개의레지스터에의해제어 SEG_Sel_Reg(Segment

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 Web server porting 2 Jo, Heeseung Web 을이용한 LED 제어 Web 을이용한 LED 제어프로그램 web 에서데이터를전송받아타겟보드의 LED 를조작하는프로그램을작성하기위해다음과같은소스파일을생성 2 Web 을이용한 LED 제어 LED 제어프로그램작성 8bitled.html 파일을작성 root@ubuntu:/working/web# vi

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 Network Programming Jo, Heeseung Network 실습 네트워크프로그래밍 멀리떨어져있는호스트들이서로데이터를주고받을수있도록프로그램을구현하는것 파일과는달리데이터를주고받을대상이멀리떨어져있기때문에소프트웨어차원에서호스트들간에연결을해주는장치가필요 이러한기능을해주는장치로소켓이라는인터페이스를많이사용 소켓프로그래밍이란용어와네트워크프로그래밍이랑용어가같은의미로사용

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 7-Segment Device Control - Device driver Jo, Heeseung HBE-SM5-S4210 의 M3 Module 에는 6 자리를가지는 7-Segment 모듈이아래그림처럼실장 6 Digit 7-Segment 2 6-Digit 7-Segment LED Controller 16비트로구성된 2개의레지스터에의해제어 SEG_Sel_Reg(Segment

More information

Microsoft PowerPoint APUE(File InO).ppt

Microsoft PowerPoint APUE(File InO).ppt 컴퓨터특강 () [Ch. 3] 2006 년봄학기 문양세강원대학교컴퓨터과학과 강의목표및내용 강의목표 파일의특성을이해한다. 파일을열고닫는다. 파일로부터데이터를읽고쓴다. 기타파일제어함수를익힌다. 강의내용 파일구조 (UNIX 파일은어떤구조일까?) 파일관련시스템호출 시스템호출의효율과구조 Page 2 1 What is a File? A file is a contiguous

More information

C# Programming Guide - Types

C# Programming Guide - Types C# Programming Guide - Types 최도경 lifeisforu@wemade.com 이문서는 MSDN 의 Types 를요약하고보충한것입니다. http://msdn.microsoft.com/enus/library/ms173104(v=vs.100).aspx Types, Variables, and Values C# 은 type 에민감한언어이다. 모든

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 (Host) set up : Linux Backend RS-232, Ethernet, parallel(jtag) Host terminal Target terminal : monitor (Minicom) JTAG Cross compiler Boot loader Pentium Redhat 9.0 Serial port Serial cross cable Ethernet

More information

<C1A63130C0E5C7C1B7CEBCBCBDBA2E687770>

<C1A63130C0E5C7C1B7CEBCBCBDBA2E687770> 제 10 장프로세스프로그래밍 프로세스시작 / 종료 자식프로세스생성 프로세스내에서새로운프로그램실행 시그널 시스템부팅 10.1 프로그램시작및종료 Unix 에서프로그램은어떻게실행이시작되고종료될까? 프로그램은 10.3 절에서살펴볼 exec 시스템호출에의해실행된다. 이호출은실행될프로그램의시작루틴에게명령줄인수 (command-line arguments) 와환경변수 (environment

More information

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

Microsoft PowerPoint - ch09 - 연결형리스트, Stack, Queue와 응용 pm0100 2015-1 프로그래밍언어 9. 연결형리스트, Stack, Queue 2015 년 5 월 4 일 교수김영탁 영남대학교공과대학정보통신공학과 (Tel : +82-53-810-2497; Fax : +82-53-810-4742 http://antl.yu.ac.kr/; E-mail : ytkim@yu.ac.kr) 연결리스트 (Linked List) 연결리스트연산 Stack

More information

Microsoft Word - FunctionCall

Microsoft Word - FunctionCall Function all Mechanism /* Simple Program */ #define get_int() IN KEYOARD #define put_int(val) LD A val \ OUT MONITOR int add_two(int a, int b) { int tmp; tmp = a+b; return tmp; } local auto variable stack

More information

chap 5: Trees

chap 5: Trees 5. Threaded Binary Tree 기본개념 n 개의노드를갖는이진트리에는 2n 개의링크가존재 2n 개의링크중에 n + 1 개의링크값은 null Null 링크를다른노드에대한포인터로대체 Threads Thread 의이용 ptr left_child = NULL 일경우, ptr left_child 를 ptr 의 inorder predecessor 를가리키도록변경

More information

Microsoft PowerPoint - 04-UDP Programming.ppt

Microsoft PowerPoint - 04-UDP Programming.ppt Chapter 4. UDP Dongwon Jeong djeong@kunsan.ac.kr http://ist.kunsan.ac.kr/ Dept. of Informatics & Statistics 목차 UDP 1 1 UDP 개념 자바 UDP 프로그램작성 클라이언트와서버모두 DatagramSocket 클래스로생성 상호간통신은 DatagramPacket 클래스를이용하여

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 Text-LCD Device Control - Device driver Jo, Heeseung M3 모듈에장착되어있는 Tedxt LCD 장치를제어하는 App 을개발 TextLCD 는영문자와숫자일본어, 특수문자를표현하는데사용되는디바이스 HBE-SM5-S4210 의 TextLCD 는 16 문자 *2 라인을 Display 할수있으며, 이 TextLCD 를제어하기위하여

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 7-SEGMENT DEVICE CONTROL - DEVICE DRIVER Jo, Heeseung 디바이스드라이버구현 : 7-SEGMENT HBE-SM5-S4210 의 M3 Module 에는 6 자리를가지는 7-Segment 모듈이아래그림처럼실장 6 Digit 7-Segment 2 디바이스드라이버구현 : 7-SEGMENT 6-Digit 7-Segment LED

More information

<4D F736F F F696E74202D20BBB7BBB7C7D15F FBEDFB0A3B1B3C0B05FC1A638C0CFC2F72E BC8A3C8AF20B8F0B5E55D>

<4D F736F F F696E74202D20BBB7BBB7C7D15F FBEDFB0A3B1B3C0B05FC1A638C0CFC2F72E BC8A3C8AF20B8F0B5E55D> 뻔뻔한 AVR 프로그래밍 The Last(8 th ) Lecture 유명환 ( yoo@netplug.co.kr) INDEX 1 I 2 C 통신이야기 2 ATmega128 TWI(I 2 C) 구조분석 4 ATmega128 TWI(I 2 C) 실습 : AT24C16 1 I 2 C 통신이야기 I 2 C Inter IC Bus 어떤 IC들간에도공통적으로통할수있는 ex)

More information

Microsoft PowerPoint - 10_Signal

Microsoft PowerPoint - 10_Signal Operating System Laboratory 시그널 - IPC - 시그널의종류 - 시그널구현함수 IPC 프로세스간통신 (Inter-Process Communication) 실행중인프로세스간에데이터를주고받는기법 IPC 에는매우많은방법이있다! File Pipe/Named pipe Socket Shared memory Message passing Remote

More information

A Hierarchical Approach to Interactive Motion Editing for Human-like Figures

A Hierarchical Approach to Interactive Motion Editing for Human-like Figures 단일연결리스트 (Singly Linked List) 신찬수 연결리스트 (linked list)? tail 서울부산수원용인 null item next 구조체복습 struct name_card { char name[20]; int date; } struct name_card a; // 구조체변수 a 선언 a.name 또는 a.date // 구조체 a의멤버접근 struct

More information

untitled

untitled 1 hamks@dongguk.ac.kr (goal) (abstraction), (modularity), (interface) (efficient) (robust) C Unix C Unix (operating system) (network) (compiler) (machine architecture) 1 2 3 4 5 6 7 8 9 10 ANSI C Systems

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 UNIX 및실습 8 장. 프로세스와사용자명령 익히기 1 학습목표 유닉스에서프로세스가무엇인지그개념을이해한다. 프로세스와관련된명령의사용방법을익힌다. 포그라운드처리와백그라운드처리의차이를이해한다. 사용자정보를보는명령의사용방법을익힌다. 2 Section 01 프로세스란 프로세스 (process) 현재시스템에서실행중인프로그램 프로세스는고유번호를가진다. Process ID

More information

제8장 프로세스

제8장 프로세스 제 8 장프로세스 리눅스시스템프로그래밍 청주대학교전자공학과 한철수 1 목차 쉘과프로세스 프로그램실행 프로그램종료 프로세스 ID 프로세스이미지 2 8.1 절 프로세스 프로세스 (process) 는파일과더불어리눅스운영체제의핵심개념중하나임. 리눅스시스템을깊이있게이해하기위해서는프로세스에대해서정확히이해해야함. 프로세스는간단히실행중인프로그램이라고할수있음. 프로그램이실행되면프로세스가됨.

More information

<C0CCBCBCBFB52DC1A4B4EBBFF82DBCAEBBE7B3EDB9AE2D313939392D382E687770>

<C0CCBCBCBFB52DC1A4B4EBBFF82DBCAEBBE7B3EDB9AE2D313939392D382E687770> i ii iii iv v vi 1 2 3 4 가상대학 시스템의 국내외 현황 조사 가상대학 플랫폼 개발 이상적인 가상대학시스템의 미래상 제안 5 웹-기반 가상대학 시스템 전통적인 교수 방법 시간/공간 제약을 극복한 학습동기 부여 교수의 일방적인 내용전달 교수와 학생간의 상호작용 동료 학생들 간의 상호작용 가상대학 운영 공지사항,강의록 자료실, 메모 질의응답,

More information

0. 표지에이름과학번을적으시오. (6) 1. 변수 x, y 가 integer type 이라가정하고다음빈칸에 x 와 y 의계산결과값을적으시오. (5) x = (3 + 7) * 6; x = 60 x = (12 + 6) / 2 * 3; x = 27 x = 3 * (8 / 4

0. 표지에이름과학번을적으시오. (6) 1. 변수 x, y 가 integer type 이라가정하고다음빈칸에 x 와 y 의계산결과값을적으시오. (5) x = (3 + 7) * 6; x = 60 x = (12 + 6) / 2 * 3; x = 27 x = 3 * (8 / 4 Introduction to software design 2012-1 Final 2012.06.13 16:00-18:00 Student ID: Name: - 1 - 0. 표지에이름과학번을적으시오. (6) 1. 변수 x, y 가 integer type 이라가정하고다음빈칸에 x 와 y 의계산결과값을적으시오. (5) x = (3 + 7) * 6; x = 60 x

More information

Chapter 4. LISTS

Chapter 4. LISTS C 언어에서리스트구현 리스트의생성 struct node { int data; struct node *link; ; struct node *ptr = NULL; ptr = (struct node *) malloc(sizeof(struct node)); Self-referential structure NULL: defined in stdio.h(k&r C) or

More information

Lab 3. 실습문제 (Single linked list)_해답.hwp

Lab 3. 실습문제 (Single linked list)_해답.hwp Lab 3. Singly-linked list 의구현 실험실습일시 : 2009. 3. 30. 담당교수 : 정진우 담당조교 : 곽문상 보고서제출기한 : 2009. 4. 5. 학과 : 학번 : 성명 : 실습과제목적 : 이론시간에배운 Singly-linked list를실제로구현할수있다. 실습과제내용 : 주어진소스를이용해 Singly-linked list의각함수를구현한다.

More information

The Pocket Guide to TCP/IP Sockets: C Version

The Pocket Guide to  TCP/IP Sockets: C Version 얇지만얇지않은 TCP/IP 소켓프로그래밍 C 2 판 4 장 UDP 소켓 제 4 장 UDP 소켓 4.1 UDP 클라이언트 4.2 UDP 서버 4.3 UDP 소켓을이용한데이터송싞및수싞 4.4 UDP 소켓의연결 UDP 소켓의특징 UDP 소켓의특성 싞뢰할수없는데이터젂송방식 목적지에정확하게젂송된다는보장이없음. 별도의처리필요 비연결지향적, 순서바뀌는것이가능 흐름제어 (flow

More information

<4D F736F F F696E74202D20BBE7BABB202D204F DC7C1B7CEBCBCBDBA20BDBAC4C9C1D9B8B528BAF1BCB1C1A12CBCB1C1A1292E707074>

<4D F736F F F696E74202D20BBE7BABB202D204F DC7C1B7CEBCBCBDBA20BDBAC4C9C1D9B8B528BAF1BCB1C1A12CBCB1C1A1292E707074> . 프로세스스케줄링 (= CPU 스케줄링 ) [ 출제빈도 상 ] - 정의 : 컴퓨터시스템의성능을높이기위해그사용순서를결정하기위한정책 - 목적 ( 성능평가 ) : 처리율증가, CPU 이용률증가, 우선순위제도, 오버헤드 ( 부하 ) 최소화, 응답시간 / 반환시간 / 최소화, 균형있는자원의사용, 무한연기회피. 프로세스스케줄링기법 ) 비선점스케줄링 (Non Preemptive)

More information

MPLAB C18 C

MPLAB C18 C MPLAB C18 C MPLAB C18 MPLAB C18 C MPLAB C18 C #define START, c:\mcc18 errorlevel{0 1} char isascii(char ch); list[list_optioin,list_option] OK, Cancel , MPLAB IDE User s Guide MPLAB C18 C

More information

<4D F736F F F696E74202D20C1A63132B0AD20B5BFC0FB20B8DEB8F0B8AEC7D2B4E7>

<4D F736F F F696E74202D20C1A63132B0AD20B5BFC0FB20B8DEB8F0B8AEC7D2B4E7> 제14장 동적 메모리 할당 Dynamic Allocation void * malloc(sizeof(char)*256) void * calloc(sizeof(char), 256) void * realloc(void *, size_t); Self-Referece NODE struct selfref { int n; struct selfref *next; }; Linked

More information

학번 : 이름 : 1. 다음파일트리구조를가진유닉스시스템이있다고가정하자. / /bin/ /home/ /home/taesoo/ /usr/ /usr/lib/ /usr/local/lib /media 모든폴더에파일이하나도없다고가정했을때사용자가터미널에서다음 ls 명령입력시화면출력

학번 : 이름 : 1. 다음파일트리구조를가진유닉스시스템이있다고가정하자. / /bin/ /home/ /home/taesoo/ /usr/ /usr/lib/ /usr/local/lib /media 모든폴더에파일이하나도없다고가정했을때사용자가터미널에서다음 ls 명령입력시화면출력 학번 : 이름 : 1. 다음파일트리구조를가진유닉스시스템이있다고가정하자. / /bin/ /home/ /home/taesoo/ /usr/ /usr/lib/ /usr/local/lib /media 모든폴더에파일이하나도없다고가정했을때사용자가터미널에서다음 ls 명령입력시화면출력을예측하시오. $ cd /usr $ ls..? $ ls.? 2. 다음그림은어떤프로세스가다음코드를수행했다는가정에서도시되었다.

More information

GNU/Linux 1, GNU/Linux MS-DOS LOADLIN DOS-MBR LILO DOS-MBR LILO... 6

GNU/Linux 1, GNU/Linux MS-DOS LOADLIN DOS-MBR LILO DOS-MBR LILO... 6 GNU/ 1, qkim@pecetrirekr GNU/ 1 1 2 2 3 4 31 MS-DOS 5 32 LOADLIN 5 33 DOS- LILO 6 34 DOS- 6 35 LILO 6 4 7 41 BIOS 7 42 8 43 8 44 8 45 9 46 9 47 2 9 5 X86 GNU/LINUX 10 1 GNU/, GNU/ 2, 3, 1 : V 11, 2001

More information

제11장 프로세스와 쓰레드

제11장 프로세스와 쓰레드 제9장자바쓰레드 9.1 Thread 기초 (1/5) 프로그램 명령어들의연속 (a sequence of instruction) 프로세스 / Thread 실행중인프로그램 (program in execution) 프로세스생성과실행을위한함수들 자바 Thread 2 9.1 Thread 기초 (2/5) 프로세스단위작업의문제점 프로세스생성시오버헤드 컨텍스트스위치오버헤드

More information

제8장 프로세스

제8장 프로세스 제 8 장프로세스 리눅스시스템프로그래밍 청주대학교전자공학과 한철수 제 8 장 목차 쉘과프로세스 프로그램실행 프로그램종료 프로세스 ID 프로세스이미지 2 8.1 절 프로세스 프로세스 (process) 는파일과더불어리눅스운영체제의핵심개념중하나임. 리눅스시스템을깊이있게이해하기위해서는프로세스에대하여정확히이해해야함. 프로세스는실행중인프로그램이라고간단히말할수있음. 프로그램이실행되면프로세스가됨.

More information

컴파일러

컴파일러 YACC 응용예 Desktop Calculator 7/23 Lex 입력 수식문법을위한 lex 입력 : calc.l %{ #include calc.tab.h" %} %% [0-9]+ return(number) [ \t] \n return(0) \+ return('+') \* return('*'). { printf("'%c': illegal character\n",

More information

Microsoft PowerPoint - polling.pptx

Microsoft PowerPoint - polling.pptx 지현석 (binish@home.cnu.ac.kr) http://binish.or.kr Index 이슈화된키보드해킹 최근키보드해킹이슈의배경지식 Interrupt VS polling What is polling? Polling pseudo code Polling 을이용한키로거분석 방어기법연구 이슈화된키보드해킹 키보드해킹은연일상한가! 주식, 펀드투자의시기?! 최근키보드해킹이슈의배경지식

More information

KEY 디바이스 드라이버

KEY 디바이스 드라이버 KEY 디바이스드라이버 임베디드시스템소프트웨어 I (http://et.smu.ac.kr et.smu.ac.kr) 차례 GPIO 및 Control Registers KEY 하드웨어구성 KEY Driver 프로그램 key-driver.c 시험응용프로그램 key-app.c KEY 디바이스드라이버 11-2 GPIO(General-Purpose Purpose I/O)

More information

Remote UI Guide

Remote UI Guide Remote UI KOR Remote UI Remote UI PDF Adobe Reader/Adobe Acrobat Reader. Adobe Reader/Adobe Acrobat Reader Adobe Systems Incorporated.. Canon. Remote UI GIF Adobe Systems Incorporated Photoshop. ..........................................................

More information