슬라이드 1

Size: px
Start display at page:

Download "슬라이드 1"

Transcription

1 Task 통신및동기화 : Message Queue, Semaphore Shared Memory Chapter #12

2 강의목차 IPC(Inter-Process Communication) 메시지큐 (Message Queue) 세마포어 (Semaphore) 공유메모리 (Shared Memory) Unix System Programming 2

3 IPC(Inter-Process Communication)

4 IPC(Inter-Process Communication) (1) 프로세스통신도구 (IPC Facilites) : 비동기적으로동작하는프로세스간의통신을위하여운영체제가제공하는도구 종류 : Signal( 신호 ) Pipe( 파이프 ) Message Queue( 메시지큐 ) Semaphore( 세마포어 ) Shared Memory( 공유메모리 ) Socket( 소켓 ) 동일한플랫폼상에서유사하게구현되어 ICP 도구로별도분류하기도함 Linux System Programming 4

5 IPC(Inter-Process Communication) (2) 프로세스통신도구 (IPC Facilites) : 세마포어 (Semaphore) 프로세스동기화와자원관리에사용 프로세스간의상호배제문제해결에사용 공유메모리 (Shared Memory) 가장빠른프로세스통신도구 하나이상의프로세스에부착하여서로공유하여접근가능 프로세스간의공유메모리접근을위해동기화가필요 메시지큐 (Message Queue) 프로세스들간에이산적인양의데이터송수신을위해사용 전송할데이터를메시지형태로생성하여전달하고메시지수신을통해데이터수신이가능 인터넷메일서비스와개념이유사 Linux System Programming 5

6 IPC(Inter-Process Communication) (3) IPC 와관련한시스템호출함수 : IPC 시스템호출함수 : get ctl op 세마포어 semget semctl semop 공유메모리 shmget shmctl 메시지큐 msgget msgctl shmop(shmat, shmdt) msgop(msgsnd, msgrcv) 기능 IPC 도구의생성및참조기능제공 소유자및접근허가변경등의기능제공 IPC 도구의연산 ( 송수신제어등 ) 기능제공 Linux System Programming 6

7 IPC(Inter-Process Communication) (4) IPC 와관련한시스템호출함수 : get 시스템호출 파일열기시스템호출 open 과유사 새롭게통신도구를생성하거나이미생성된통신도구에대한 id 를반환하여접근가능하게함 반환된 id 는파일디스크립터와비슷하게동작 접근허가또한파일접근허가와비슷하게규정 ctl 시스템호출 통신도구에관한상태정보읽기 몇몇상태정보 ( 소유자, 그룹, 접근허가등 ) 에대한변경 통신도구의제거기능 op 시스템호출 프로세스간의데이터전송을실행 파일시스템호출 read/write 와유사 Shmat 는파일의 open 과유사하고, shmdt 는파일의 close 와유사 Linux System Programming 7

8 IPC(Inter-Process Communication) (5) IPC 도구식별자 : IPC 도구식별자 IPC key 파일을식별하기위해파일이름을사용하듯이 IPC 객체를식별하기위해사용하는정수형숫자 프로세스들은 IPC key를이용하여 IPC 자원을공유 자료형 : key_t (<sys/types.h> 에정의 ) char device Inode # of file key_t IPC key 변환시스템호출 ftok(file_to_key) IPC 도구의공유를편리하게지원하기위해파일경로명과식별자를 IPC 도구에부여하고, 이를 IPC key 값으로변환하는시스템호출 Linux System Programming 8

9 IPC(Inter-Process Communication) (6) IPC 도구식별자 : IPC key 변환시스템호출 ftok(file_to_key) Linux System Programming 9

10 IPC(Inter-Process Communication) (7) IPC 도구의상태자료구조 : 생성된 IPC 객체에대한상태정보를저장하는구조체 IPC 도구유형별로별도의상태구조체를지원하나다음의접근허가구조를공통으로포함한다 IPC 도구의접근허가구조 : struct ipc_perm 파일의접근허가와유사한기능을지원 접근모드에서실행모드는무의미함 Linux System Programming 10

11 IPC(Inter-Process Communication) (8) IPC 도구테이블 IPC 도구유형별로생성된 IPC 객체를관리하기위해운영체제가유지하는테이블 IPC 도구유형별로각각의테이블을유지 파일테이블과유사한개념 Linux System Programming 11

12 IPC(Inter-Process Communication) (9) IPC 도구관리명령 : ipcs 명령 현재사용중인 IPC 도구들의상태 (status) 를보여주는명령 IPC 타입, 사용자 ID, key 값그리고접근허가등을볼수있음 옵션을사용하여지정된유형의 IPC 도구상태정보만을접근가능 -q : 메시지큐, -m : 공유메모리, -s : 세마포어 ipcrm 명령 IPC 객체를제거하는명령 IPC 도구유형및 key 값을지정하는원하는 IPC 객체를제거 Linux System Programming 12

13 Message Queue

14 메시지큐 (Message Queue) (1) 메시지큐 (Message Queue) 프로세스간에이산적인데이터를메시지형태로전송하는통신도구 파이프와같이 FIFO 타입의데이터전송을지원 메시지는메시지와바이트 (byte) 들의모임으로구성 메시지유형은정수값으로여러가지메시지형태에 id를부여하여구별하기위해사용 바이트모임은전송하는데이터를의미하는것으로문자, 그림또는일련의구조체데이터등을전송하기위햇사용 관련시스템호출함수 msgget() 메시지큐를생성 msgsnd()/msgrcv() 메시지전송및수신 msgctl() 메시지큐제어 Linux System Programming 14

15 메시지큐 (Message Queue) (2) 메시지큐의구조 : 메시지큐의상태구조체 : msgid_ds 메시지큐객체의상태정보를저장하는구조체 하나의메시지큐가생성되면하나의 msgid_ds 구조체가생성 Linux System Programming 15

16 메시지큐 (Message Queue) (3) 메시지큐의동작 : 전송프로세스가전송할데이터를메시지형태로만들어메시지를전송하면전송된메시지는메시지큐의마지막에연결된다 수신프로세스는메시지큐에존재하는메시지를선택적으로수신할수있다. 수신프로세스에서는메시지를수신할때에다음의수신정책중에하나를지정하여야한다. 메시지큐에서첫번째메시지 메시지큐에서지정된타입의첫번째메시지 메시지큐에있는타입들의범위들로부터첫번째메시지 Linux System Programming 16

17 메시지큐 (Message Queue) (4) 메시지큐의생성 : msgget() 메시지큐생성시스템호출 주어진 key 를갖는메시지큐가존재하면메시지큐의 id 를반환하고, 그렇지않으면새롭게메시지큐를생성하고 id 를반환 Linux System Programming 17

18 메시지큐 (Message Queue) (5) Linux System Programming 18

19 메시지큐 (Message Queue) (6) 메시지큐의생성 : msgget() msgget() 시스템호출의 flag 옵션 Linux System Programming 19

20 메시지큐 (Message Queue) (7) 메시지큐구조체 : msqid_ds Linux System Programming 20

21 메시지큐 (Message Queue) (8) 메시지큐구조체초기값 Linux System Programming 21

22 메시지큐 (Message Queue) (9) 메시지큐의제어 : msgctl() 메시지큐제어시스템호출 메시지큐의상태를질의하거나상태정보를변경, 또는메시지큐를제거하는기능을지원 Linux System Programming 22

23 메시지큐 (Message Queue) (10) 메시지큐의제어 : msgctl() msgctl() 시스템호출의명령어 Linux System Programming 23

24 메시지큐 (Message Queue) (11) msgctl() 시스템호출의사용예 메시지큐관련자료구조선언 #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> int msqid; struct msqid_ds ds; 메시지큐의제거 msgctl(msqid, IPC_RMID, (struct msqid_ds *)0); 메시지큐의소유자변경 msgctl(msqid, IPC_STAT, &ds); ds.msg_perm.uid = 51; msgctl(msqid, IPC_SET, &ds); Linux System Programming 24

25 메시지큐 (Message Queue) (12) msgctl() 시스템호출의사용예 메시지큐의접근허가변경 msgctl(msqid, IPC_STAT, &ds); ds.msg_perm.mode = 0660; msgctl(msqid, IPC_SET, &ds); 메시지큐의메시지크기변경 msgctl(msqid, IPC_STAT, &ds); ds.msg_qbytes = 5000; msgctl(msqid, IPC_SET, &ds); Linux System Programming 25

26 메시지큐 (Message Queue) (13) 메시지큐의연산 : msgsnd(), msgrcv() 메시지구조체 : #include <sys/msg.h> struct msgbuf { long mtype; /* 메시지유형 */ char mtext[1]; /* 메지시텍스트 */ 메시지유형은전송되는여러가지유형의메시지형태를분류하여지정 메시지텍스트는전송하는데이터를저장 메시지텍스트의크기는최소 0에서최대 64 KB 이내이며, 묵시적으로 2048 바이트로사용 Linux System Programming 26

27 메시지큐 (Message Queue) (14) 메시지송신시스템호출 : msgsnd() Linux System Programming 27

28 메시지큐 (Message Queue) (15) 메시지송신시스템호출 : msgsnd() msgsnd 시스템호출에의한메시지큐구조체변경 Linux System Programming 28

29 메시지큐 (Message Queue) (16) 메시지수신시스템호출 : msgrcv() Linux System Programming 29

30 메시지큐 (Message Queue) (17) 메시지수신시스템호출 : msgrcv() msgrcv() 시스템호출에서의메시지타입지정 Linux System Programming 30

31 예제프로그램 #1 (1) 하나의메시지를전송하고수신하는프로그램 // file name : ex9-1a.c // #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> struct { long t; char a[60]; x = {11L,"hello"; main() { int mid; mid = msgget(11l,ipc_creat 0666); msgsnd(mid,&x,strlen(x.a)+1,0); sleep(60); msgctl(mid,ipc_rmid,0); Linux System Programming 31

32 예제프로그램 #1 (2) // file name : ex9-1b.c // #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> struct { long t; char a[60]; x ; main() { int mid,rtn; mid = msgget(11l,0); rtn=msgrcv(mid,&x,60,0l,0); printf("rtn=%d type=%d text=%s\n",rtn,x.t,x.a); Linux System Programming 32

33 예제프로그램 #2 (1) 예제프로그램 #1 을개선하여여러개의메시지를송수신하는프로그램 // file name : ex9-2a.c // #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #define MAX_SEND_SZ 30 #define DONE 99L main() { void perror(); key_t key; int mid; static struct { long mtype; char mtext[max_send_sz]; buf; Linux System Programming 33

34 예제프로그램 #2 (2) static char *string[3] = { "hello", "how are you", "good-bye"; int i,rtn; if((key= ftok(".",'a'))==-1) { perror("can\'t form key"); exit(1); mid = msgget(key,ipc_creat 0660); if(mid == -1) { perror("sender can not make msg queue!"); exit(2); Linux System Programming 34

35 예제프로그램 #2 (3) buf.mtype = 1L; for(i=0;i<3;i++) { strcpy(buf.mtext,string[i]); if(msgsnd(mid,&buf,strlen(buf.mtext)+1,0)==-1) { perror("sender can not msgsnd!"); exit(3); rtn = msgrcv(mid,&buf,max_send_sz,done,0); if(rtn == -1) { perror("sender can not msgrcv"); exit(4); msgctl(mid,ipc_rmid,0); Linux System Programming 35

36 예제프로그램 #2 (4) // file name : ex9-2b.c // #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #define MAX_RECV_SZ 60 #define FIFO 0L #define ZERO_LEN 0 #define DONE 99L static struct { long mtype; char mtext[max_recv_sz]; buf; key_t key; int mid; int rtn; Linux System Programming 36

37 예제프로그램 #2 (5) int main(int argv,char *argc[]) { void perror(); if((key= ftok(".",'a'))==-1) { perror("can\'t form key"); exit(1); mid = msgget(key,0); if(mid == -1) { perror("receiver can not access msg queue!"); exit(2); while(1) { rtn = msgrcv(mid,&buf,max_recv_sz,fifo,0); printf("rtn=%d buf.mtype=%ld buf.mtext=%s\n", rtn,buf.mtype,buf.mtext); if(!strcmp(buf.mtext,"good-bye")) break; buf.mtype = DONE; msgsnd(mid,&buf,zero_len,0); exit(0); 37

38 예제프로그램 #3 (1) 메시지송신프로그램가키보드입력을메시지로만들어여러개의수신프로그램에전달하는프로그램 송신프로그램은 fork()/exec() 시스템호출을통하여수신프로세스를생성하고, 수신프로세스는수신된메시지를표준출력으로출력하도록한다. // file name : ex9-3a.c // #include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #define MAX_SZ 80 #define NCHILD 3 Linux System Programming 38

39 예제프로그램 #3 (2) #define WAIT_SOLE_USE(MSGQID) { \ int still_active = NCHILD; \ int i; \ long s_pid; \ s_pid = getpid(); \ while(still_active) { for(i=0;i<nchild;i++) \ if(msgrcv(msgqid,&buf,max_sz,s_pid,ipc_nowait)!= -1) \ if(!strncmp(buf.mtext,"done",4)) still_active--; \ sleep(2); \ \ int main(void) { void perror(); key_t ftok(); int msgqid; struct { long mtype; char mtext[max_sz]; buf; Linux System Programming 39

40 예제프로그램 #3 (3) int msg_length; static char qid_evar[40]; static char *envp[2] = { qid_evar ; int this_fork, child; long r_pid[nchild]; char child_name[20]; int eof = 0; if((msgqid = msgget(ipc_private,ipc_creat 0660)) == -1) { perror("sender can't make message queue!"); exit(1); sprintf(qid_evar,"mqid=%d",msgqid); for(child=0;child<nchild;child++) { this_fork = fork(); if(this_fork == -1) { perror("fork failed"); exit(2); else if(this_fork == 0) { sprintf(child_name,"mwall_r%d",child); execle("ex9-3b",child_name,0,envp); perror("exec failed"); exit(3); Linux System Programming 40

41 예제프로그램 #3 (4) else r_pid[child] = (long) this_fork; setbuf(stdout,(char *) 0); while(1) { fprintf(stdout, "Enter message to be sent to all receivers:"); if(gets(buf.mtext) == (char *) 0) { fprintf(stdout,"\n"); eof++; strcpy(buf.mtext,"eof"); msg_length = strlen(buf.mtext) +1; for(child=0;child<nchild;child++) { buf.mtype = r_pid[child]; if(msgsnd(msgqid,&buf,msg_length,0) == -1) { perror("producer msgsnd error"); exit(4); if(eof) break; sleep(1); Linux System Programming 41

42 예제프로그램 #3 (5) WAIT_SOLE_USE(msgqid); msgctl(msgqid,ipc_rmid,0); exit(0); Linux System Programming 42

43 // file name : ex9-3b.c // #include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/msg.h> #define MAX_SZ 80 예제프로그램 #3 (6) int main(int argc, char *argv[]) { void perror(); char *getenv(); long pid; char *valuep; int msgqid; struct { buf; long mtype; char mtext[max_sz]; Linux System Programming 43

44 예제프로그램 #3 (7) pid = (long) getpid(); if((valuep = getenv("mqid")) == NULL) { fprintf(stderr,"%s:can't get env MQID\n",argv[0]); exit(1); else sscanf(valuep,"%d",&msgqid); while(1) { msgrcv(msgqid,&buf,max_sz,pid,msg_noerror); printf("%s received '%s'\n",argv[0],buf.mtext); if(!strcmp(buf.mtext,"eof")) break; buf.mtype = (long) getppid(); strcpy(buf.mtext,"done"); if(msgsnd(msgqid,&buf,strlen(buf.mtext),0) == -1) { fprintf(stderr,"%s:msgsnd error\n",argv[0]); exit(2); exit(0); Linux System Programming 44

45 Semaphore

46 세마포어 (Semaphore) (1) 세마포어 (Semaphore) 실행단위 ( 프로세스또는쓰레드 ) 간의동기화도구 2개의원자적연산 P와 V가정의되어있는, 정수값을가지는객체 s : 세마포어 P(s) : if ( s > 0 ) then s-- else 현재프로세스는대기한다 ; V(s) : if ( 1개이상의프로세스가대기중 ) then 1개프로세스만진행한다 else s++; 일상생활에서의 신호등 과같은동작을수행 철도교통을통제하기위한깃발신호로부터유래 Linux System Programming 46

47 세마포어 (Semaphore) (2) 세마포어 (Semaphore) ( 계속 ) 세마포어연산 P & V 는원자적연산 (atomic operation) 하나의프로세스가 P 또는 V 연산을실행하는도중에는중지하지않는다 어떤프로세스가 P 또는 V 연산을이용하여세마포어에접근하는동안에는다른프로세스가세마포어값을변경할수없다 세마포어의활용 상호배제 (mutual exclusion) 문제 두개이상의프로세스가하나의공유자원을접근할때에한순간에하나의프로세스만공유자원을접근할수있도록보장함 실행동기화 두개이상의프로세스간에실행순서에맞추어실행됨을보장함 Linux System Programming 47

48 세마포어 (Semaphore) (3) 세마포어종류 : 이진세마포어 (Binary Semaphore) 0 또는 1의정수값만가지는세마포어 P(s) 연산은세마포어 s가 1일때에 0으로변경 V(s) 연산은세마포어 s가 0일때에 1로변경 하나의자원에대한공유및동기화를지원 계수형세마포어 (Counting Semaphore) 범위에제한이없는정수값을가지는세마포어 일반적으로언급하는세마포어 다수의공유자원에대해여러프로세스가접근할때에상호배제및동기화를지원 Linux System Programming 48

49 세마포어 (Semaphore) (4) 세마포어이용 - 공유자원에대한상호배제 (Mutual Exclusion) 여러개의프로세스가하나의자원을공유하는경우, 동시에여러프로세스가자원을접근하면예상하지못하는문제가발생함 예 : 동시에여러프로그램이프린터에출력을시도하는경우 해결책 상호배제 한순간에하나의프로세스만공유자원을접근함을보장함 임계영역 (Critical Section) : 전체프로그램중에서공유자원을접근하는프로그램영역 한순간에임계영역을실행하는프로세스는하나만존재하도록보장함 세마포어를이용하여상호배제를구현 공유자원의갯수에따라이진세마포어또는계수형세마포어를사용 공유자원에대한잠금과풀기 (lock & unlock) 기능을지원 Linux System Programming 49

50 세마포어 (Semaphore) (5) 세마포어이용 - 공유자원에대한상호배제 (Mutual Exclusion) 프로세스 P1 세마포어 s ( 초기값 : 1) 프로세스 P2 P(s) P(s) Critical Section 공유자원 Critical Section V(s) V(s) Linux System Programming 50

51 세마포어 (Semaphore) (6) 세마포어이용 - 프로세스간의실행동기화 (Synchronization) 하나의프로그램이여러개의프로세스로이루어지는경우, 프로세스간의종속성에의해실행순서가정해지며, 반드시실행순서에의해동작하여함 예 : 하나의프로세스가다른프로세스가제공하는데이터를받아동작하는경우 해결책 프로세스실행동기화 프로세서 P1가 T1 문장을실행한후에프로세스 P2가 T2 문장을실행하여야하는경우 프로세스 P2는 T2 문자을실행하기전에프로세스 P1이 T1 문장을실행하여는지를검사 프로세스 P1이 T1 문장을실행하였으면바로 T2 문장을실행프로세스 P1이 T2 문장을실행하지않았으면실행할때까지대기 세마포어를이용하여동기화를지원함 대개의경우이진세마포어를사용 Linux System Programming 51

52 세마포어 (Semaphore) (7) 세마포어이용 - 프로세스간의실행동기화 (Synchronization) 프로세스 P1 세마포어 s ( 초기값 : 0) 프로세스 P2 V(s) T1: P(s) T2: Linux System Programming 52

53 세마포어 (Semaphore) (8) 세마포어의생성 : semget() Linux System Programming 53

54 세마포어 (Semaphore) (9) 세마포어의생성 : semget() Linux System Programming 54

55 세마포어 (Semaphore) (10) 세마포어의생성 : semget() semget() 시스템호출의동작 세마포어구조체초기화 : Linux System Programming 55

56 세마포어 (Semaphore) (11) 세마포어의제어 : semctl() 세마포어제어연산 1. 세마포어의집합안에개별적인세마포어나모든세마포어에 대해세마포어값을읽어오거나새로운값을설정 2. 세마포어집합의상태정보을읽어오거나변경 3. 세마포어에서대기중인프로세스의수를결정 4. 마지막으로세마포어를연산한프로세스를결정 5. 세마포어를제거 semctl () 시스템호출을통해상기의세마포어제어연산을실행 Linux System Programming 56

57 세마포어 (Semaphore) (12) 세마포어의제어 : semctl() Linux System Programming 57

58 세마포어 (Semaphore) (13) 세마포어의제어 : semctl() semctl() 시스템호출의명령어및반환값 Linux System Programming 58

59 세마포어 (Semaphore) (14) 세마포어의제어 : semctl() 세마포어생성 #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #define ANY 0 int semid, rtn; struct semid_ds semds; ushort us[5], init_us[5] = {0, 6, 7, 1, 4; semid = semget(key, 5, IPC_CREAT 0666); 세마포어집합에서하나의세마포어를초기화 semctl(semid, 2, SETVAL, 7); 세마포어집합에서하나의세마포어값읽기 // GETCNT, GETZCNT, GETPID도같은형태로사용 semctl(semid, 2, GETVAL, Linux ANY); System Programming 59

60 세마포어 (Semaphore) (15) 세마포어의제어 : semctl() 세마포어집합내의모든세마포어의값을초기화 semctl(semid, ANY, SETALL, init_us); 세마포어집합내의모든세마포어의값읽기 semctl(semid, ANY, GETALL, us); 세마포어의소유자변경 // 접근허가모드변경에도같은형태로사용 semctl(semid, ANY, IPC_STAT, &semds); semds.sem_perm.uid = 51; semctl(semid, ANY, IPC_SET, &ds); 세마포어집합제거 semctl(semid, ANY, IPC_RMID, ANY); Linux System Programming 60

61 세마포어 (Semaphore) (16) 세마포어의연산 : semop() 세마포어의값을증가시키거나감소시키는연산을수행 Linux System Programming 61

62 세마포어 (Semaphore) (17) Linux System Programming 62

63 세마포어 (Semaphore) (18) Linux System Programming 63

64 예제프로그램 #4 (1) 세마포어를이용하여공유자원에대한접근을제어하는프로그램 공유자원은표준출력 // file name : ex10-1.c // #include <sys/ipc.h> #include <sys/sem.h> #include <stdio.h> #define DUMMY 0 #define COUNT 4 int main(int argc, char *argv[]) { key_t ipckey; /* modified */ int semid, semget(),semctl(),semop(); int pid,getpid(); int creator,i; static struct sembuf lock = {0,-1,SEM_UNDO; static struct sembuf unlock = {0, 1,SEM_UNDO; setbuf(stdout,(char *) NULL); 64

65 예제프로그램 #4 (2) ipckey = ftok(argv[0],'s'); if((semid = semget(ipckey,1,ipc_creat IPC_EXCL 0666))!= -1) { creator = 1; else { if((semid = semget(ipckey,1,0)) == -1) { perror(argv[0]); exit(1); creator = 0; if(creator) { if(semctl(semid,0,setval,1) == -1) { perror(argv[0]); exit(2); pid = getpid(); for(i=0;i<count;i++){ if(semop(semid,&lock,1) == -1) { perror(argv[0]); exit(3); printf("\t[%d]locking\t",pid); sleep(1); printf("[%d] unlocking\n",pid); Linux System Programming 65

66 예제프로그램 #4 (3) if (semop(semid,&unlock,1) == -1) { perror(argv[0]); exit(4); if (creator) { sleep(5); if(semctl(semid,dummy,ipc_rmid,dummy) == -1) { perror(argv[0]); exit(5); Linux System Programming 66

67 예제프로그램 #5 (1) 다음그림과세개의세마포어를갖는세마포어집합을이용하여프린터자원을관리하는프로그램첫번째세마포어는두개의프린터모두를관리하는계수형세마포어두번째및세번째세마포어는각각프린터1과프린터2를관리하는세마포어프린터는단말기장치를 PRINTER1으로, 정규파일을 PRINTER2로환경변수를정의하여시뮬레이션한다 67

68 #include <fcntl.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #include <stdio.h> #include "ex10-2.h" #define DUMMY 0 #define NUMPR 2 #define ACQUIRE -1 #define RELEASE 1 예제프로그램 #5 (2) int main(int argc,char *argv[]) { char *getenv(), *printer[numpr], buf[bufsiz]; key_t ipckey; /* modified */ int semid, semget(), semctl(), semop(); ushort initial[numpr +1]; int i, prntnum, creator, getpid(); int n, fdin, fdout; struct sembuf operation[2]; char errmsg[30]; if((printer[1] = getenv("printer1")) == (char *) NULL (printer[2] = getenv("printer2")) == (char *) NULL) { printf("missing printer assignment\n"); exit(1); 68

69 예제프로그램 #5 (3) if(strncmp(argv[0],"line",4) ==0) prntnum = 1; else if(strncmp(argv[0],"lase",4) ==0) prntnum =2; else prntnum = getpid() % NUMPR +1; ipckey = ftok(argv[0], 's'); if((semid = semget(ipckey,numpr +1,IPC_CREAT IPC_EXCL 0666))!= -1) { creator = 1; else { if((semid = semget(ipckey, NUMPR +1, 0666)) == -1) { sprintf(errmsg, "%s - semget", argv[0]); perror(errmsg); exit(2); if(creator) { /* initialize semaphore set */ initial[0] = NUMPR; for(i=1; i<= NUMPR; i++) initial[i] = 1; if(semctl(semid, DUMMY, SETALL, initial) == -1) { sprintf(errmsg,"%s -SETALL", argv[0]); perror(errmsg); exit(3); operation[1].sem_num = prntnum; operation[1].sem_op = ACQUIRE; operation[1].sem_flg = SEM_UNDO; operation[0].sem_num = 0; operation[0].sem_op = ACQUIRE; operation[0].sem_flg = SEM_UNDO; 69

70 예제프로그램 #5 (4) if(semop(semid, operation, 2) == -1) { sprintf(errmsg,"%s - ACQUIRE", argv[0]); perror(errmsg); exit(4); if((fdin = open(argv[1], O_RDONLY)) == -1) { sprintf(errmsg,"%s - %s", argv[0], argv[1]); perror(errmsg); exit(5); if((fdout = open(printer[prntnum], O_CREAT O_WRONLY)) == -1) { sprintf(errmsg,"%s - %s", argv[0], printer[prntnum]); perror(errmsg); exit(6); while((n= read(fdin, buf, BUFSIZ)) > 0) write(fdout, buf, n); operation[1].sem_op = RELEASE; operation[0].sem_op = RELEASE; if(semop(semid, operation, 2) == -1) { sprintf(errmsg,"%s - RELEASE", argv[0]); perror(errmsg); exit(7); exit(0); 70

71 예제프로그램 #6 (1) 다음그림과같은생산라인을시뮬레이션하는프로그램각공정은다중프로세스를생성하고이들의생산순서와소비시간을세마포어와프로세스수면 (sleep) 을이용하여시뮬레이션한다 71

72 예제프로그램 #6 (2) // // header file name : ex10-3.h // #define NWIDGETS 5 #define PARTA 0 #define PARTB 1 #define PARTC 2 #define SUB1 3 #define HOLDER 0 72

73 예제프로그램 #6 (3) // // source file name : ex10-3a.c // #include <signal.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #include "ex10-3.h" int semprodn; void endsim(); int main(int argc, char *argv[]) { int widget; int pgrp; char asc_prod_key[20]; static struct sembuf partc_sub1[2] = { { PARTC, -1, SEM_UNDO, { SUB1, -1, SEM_UNDO ; if((semprodn=semget(ipc_private,4,ipc_creat 0640)) == -1) { printf("can't get production line semaphore set\n"); exit(1); 73

74 예제프로그램 #6 (4) signal(sigint, endsim); sprintf(asc_prod_key,"%d", semprodn); if( fork() == 0) execl("ex10-3b","a", asc_prod_key, (char *)0); if( fork() == 0) execl("ex10-3b","b", asc_prod_key, (char *)0); if( fork() == 0) execl("ex10-3b","c", asc_prod_key, (char *)0); if( fork() == 0) execl("ex10-3c","ex10-3c", asc_prod_key, (char *)0); for(widget=1; widget < NWIDGETS; widget++) { semop(semprodn, partc_sub1, 2); printf("%s: ready to make widget #%d\n", argv[0], widget); endsim(); void endsim() { semctl(semprodn, 0,IPC_RMID, 0); signal(sigterm, SIG_IGN); kill(0, SIGTERM); exit(0); 74

75 예제프로그램 #6 (5) // // source file name : ex10-3b.c // #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #include "ex10-3.h" int main(int argc, char *argv[]) { int semprodn, index; int unit = 0; static struct sembuf parti = { HOLDER, 1, SEM_UNDO ; static int prodtimeabc[3] = {2,3,4; semprodn = atoi( argv[1] ); index = argv[0][0]- 'a'; /* argv[0] == [abc] */ parti.sem_num = index; while(1) { semop(semprodn, &parti, 1); printf("%s: producing unit #%d\n", argv[0], ++unit); sleep(prodtimeabc[index]); 75

76 예제프로그램 #6 (6) // // source file name : ex10-3c.c // #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #include "ex10-3.h" int main(int argc, char *argv[]) { int semprodn; int unit = 0; static struct sembuf part_ab[2] = { {PARTA, -1, SEM_UNDO, {PARTB, -1, SEM_UNDO ; static struct sembuf sub1 = { SUB1, 1, SEM_UNDO ; semprodn = atoi( argv[1] ); while(1) { semop(semprodn, part_ab, 2); semop(semprodn, &sub1, 1); printf("%s: producing sub-assembly #%d\n", argv[0], ++unit); 76

77 Shared Memory

78 공유메모리 (Shared Memory) (1) 공유메모리 (Shared memory) 두개이상의프로세스가실제메모리의일부를공유하여통신할수있는 IPC 도구 통신하려는프로세스는우선공유메모리를할당받는다 프로세스는할당된공유메모리를자신의가상주소공간일부에붙여 (attach) 메모리에데이터를읽고쓰는것가동일한방법으로필요한데이터를읽거나전송하려는데이터를기록하여상호통신한다 프로세스간의통신이종료되면공유메모리를가상주소공간에서떼어내고 (detach) 공유메모리를해제한다 IPC 도구중에서가장효율적 시스템간의이식성이낮음 프로세스간의메모리공유를위해별도의하드웨어지원이필요 공유메모리를사용한프로그램을하드웨어지원이없는시스템에서는사용불가 Linux System Programming 78

79 공유메모리 (Shared Memory) (2) 공유메모리시스템호출 : shmget 공유메모리를새롭게할당하거나할당된공유메모리의핸들을반환한다 shmctl 공유메모리와관련된상태변수값을변경하거나공유메모리를제거한다 shmat 공유메모리를프로세스의가상주소공간에논리적으로부착 (attach) 한다 shmdt 프로세스의가상주소공간으로부터공유메모리를분리한다 Linux System Programming 79

80 공유메모리 (Shared Memory) (3) 공유메모리시스템호출 : shmget() 프로세스 P1 공유메모리 프로세스 P2 shmat() shmat() 가상주소 : shmdt() shmdt() 가상주소 : shmctl() Linux System Programming 80

81 공유메모리 (Shared Memory) (4) 공유메모리의생성 : shmget() Linux System Programming 81

82 공유메모리 (Shared Memory) (5) 공유메모리의생성 : shmget() 공유메모리구조체 Linux System Programming 82

83 공유메모리 (Shared Memory) (6) 공유메모리의생성 : shmget() 공유메모리구조체의초기화 Linux System Programming 83

84 공유메모리 (Shared Memory) (7) 공유메모리의제어 : shmctl() Linux System Programming 84

85 공유메모리 (Shared Memory) (8) 공유메모리의제어 : shmctl() shmctl() 시스템호출의명령어 Linux System Programming 85

86 공유메모리 (Shared Memory) (9) 공유메모리의연산 : shmat() / shmdt() Linux System Programming 86

87 예제프로그램 #7 (1) 학원강좌예약시스템프로그램 부모프로세스는강좌예약정보를갖는공유메모리을할당하고, 공유메모리에대한상호배제를위한세마포어를생성한다자식프로세스을생성하여강좌예약을수행하는데, 자식프로세스는주기적으로강좌예약을수행하도록시뮬레이션하며, 더이상예약할좌석 (seat) 가없으면종료한다부모프로세스는모든자식프로세스가종료할때까지기다렸다가세마포어와공유메모리를제거하고종료한다 // // file name: ex11-1.h // struct CLASS { char class_number[6]; char date[6]; char title[50]; int seats_left; typedef struct CLASS class_t; 87

88 // file name: ex11-1a.c // #include <stdio.h> #include <memory.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #include <sys/shm.h> #include "ex11-1.h" 예제프로그램 #7 (2) class_t class = { "1001", "120186", "C Language for Programmers", 15 ; #define NCHILD 3 int child[nchild]; char int char char void *shm_ptr, *shmat(); semid, shmid; ascsemid[10], ascshmid[10]; pname[14]; rpterror(); int main(int argc, char *argv[]) { Linux System Programming 88 int i;

89 예제프로그램 #7 (3) strcpy(pname, argv[0]); shm_init(); sem_init(); for(i=0; i < NCHILD; i++) { child[i] = fork(); switch(child[i]) { case -1: rpterror("fork-failure"); exit(1); case 0: sprintf(pname,"ex11-1b%d",i+1); execl("ex11-1b", pname, ascshmid, ascsemid, (char *) 0); perror("execl faild"); exit(2); wait_and_wrap_up(); shm_init() { shmid=shmget(ipc_private, sizeof(class), 0600 IPC_CREAT); if(shmid == -1) { perror("shmget failed"); exit(3); shm_ptr = shmat(shmid, (char *) 0, 0); if(shm_ptr == (char *) -1) { perror("shmat failed"); exit(4); memcpy(shm_ptr,(char *) &class, sizeof(class)); sprintf(ascshmid,"%d", shmid); 89

90 예제프로그램 #7 (4) sem_init() { if((semid=semget(ipc_private, 1, 0600 IPC_CREAT)) == -1) { perror("semget failed"); exit(5); if((semctl(semid, 0, SETVAL,1)) == -1) { printf("parent: semctl, SETVAL failed\n"); exit(6); sprintf(ascsemid,"%d",semid); wait_and_wrap_up() { int wait_rtn, w, ch_active = NCHILD; while(ch_active > 0) { wait_rtn = wait((int *) 0); for(w=0; w < NCHILD; w++) if(child[w] == wait_rtn) { ch_active--; break; printf("parent removing shm and sem\n"); shmdt(shm_ptr); shmctl(shmid, IPC_RMID); semctl(semid, 0, IPC_RMID, 0); exit(0); 90

91 예제프로그램 #7 (5) void rpterror(char *string) { char errline[50]; sprintf(errline,"%s %s",string, pname); perror(errline); 91

92 // file name: ex11-1b.c // #include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #include <sys/shm.h> #include "ex11-1.h" 예제프로그램 #7 (6) class_t *class_ptr; char *memptr, *shmat(), *pname; int semid, shmid, ret; struct sembuf lock = { 0, -1, 0; struct sembuf unlock = { 0, 1, 0; void rpterror(); int main(int argc, char *argv[]) { if(argc < 3) { fprintf(stderr, "Usage: %s shmid semid\n", argv[0]); exit(1); pname = argv[0]; sscanf(argv[1],"%d", &shmid); memptr = shmat(shmid, (char *) 0, 0); 92

93 예제프로그램 #7 (7) if(memptr == (char *) -1) { rpterror("shmat failed"); exit(2); class_ptr = (class_t *) memptr; sscanf(argv[2], "%d", &semid); sell_seats(); ret = shmdt(memptr); exit(0); sell_seats() { int all_out = 0; srand((unsigned) getpid()); while(! all_out) { /* loop to sell all seats */ if(semop(semid, &lock, 1) == -1) { rpterror("semop lock failed"); exit(4); if(class_ptr -> seats_left > 0) { class_ptr -> seats_left--; printf("%s SOLD SEAT -- %2d left\n", pname, class_ptr->seats_left); 93

94 예제프로그램 #7 (8) else { all_out++; printf("%s sees no seats left\n", pname); ret = semop(semid, &unlock, 1); if(ret ==-1) { rpterror("semop unlock failed"); exit(4); sleep((unsigned) rand() %10 +1); void rpterror(string) char *string; { char errline[50]; sprintf(errline,"%s %s",string, pname); perror(errline); 94

95 예제프로그램 #8 (1) 세마포어와공유메모리를이용하여버퍼의자료를생산하고소비하는생산자 / 소비자 (producer/consumer) 프로그램생산자는공유메모리를할당하여버퍼를설정한다생산자와소비자사이에버퍼접근을위한동기화를위해 2 개의세마포어를생성하여사용한다 버퍼쓰기동기화 (consumed 동기화 ) - 생산자는소비자가버퍼의자료를읽고간후에새로운자료를버퍼에쓴다 버퍼읽기동기화 (produced 동기화 ) - 소비자는생산자가버퍼에새로운자료를쓴후에자료를읽어간다 95

96 예제프로그램 #8 (2) // file name: ex11-2a.c // /* producer program: producer program sets up a buffer to be read by a consumer. semaphore are used to ensure taht producer dosen't overwrite an unread buffer and consumer dosen't read the same data more than once. */ #include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #include <sys/shm.h> #define MSG_SIZE 30 #define MAX 5 main() { char *getenv(); key_t ftok(); char *shmat(); key_t key; void perror(), exit(); 96

97 예제프로그램 #8 (3) /* two semaphores in a set index 0 - incremented when producer has reset buffer - tested and decremented by consumer to check if buffer has been reset index 1 - incremented when consumer has read buffer - tested and decremented by producer to check if consumer is done. */ static struct sembuf wait_consumed = { 1, -1, 0; static struct sembuf signal_produced = { 0, 1, 0; int semid, shmid; char *message; int i; if((key = ftok(getenv("home"), 'u')) == (key_t) -1) { fprintf(stderr,"ftok key formation error\n"); exit(1); semid = semget(key, 2, IPC_CREAT 0660); if(semid == -1) { perror("producer semget():"); exit(2); 97

98 예제프로그램 #8 (4) shmid = shmget(key, MSG_SIZE, IPC_CREAT 0660); if(semid == -1) { perror("producer shmget():"); exit(3); message = shmat(shmid, (char *) 0, 0); for(i=1; i < MAX; i++) { /* producer has to go first */ if(i>1) semop(semid, &wait_consumed, 1); sprintf(message, "message %d", i); semop(semid, &signal_produced, 1); shmdt(message); sleep(5); /* allow consumer to digest last message */ /* alternatively a DELIMITER string could be placed in shared memory when seen by the consumer, it would exit. the producer would do shmctl (..., IPC_STAT,...) and when shm_attach == 1, it would remove the two IPC facilities */ shmctl(shmid, IPC_RMID, (struct shmid_ds *) 0); shmctl(shmid, 0, IPC_RMID); 98

99 예제프로그램 #8 (5) // file name: ex11-2b.c // /* consumer program: producer program sets up a buffer to be read by a consumer. semaphore are used to ensure taht producer dosen't overwrite an unread buffer and consumer dosen't read the same data more than once. */ #include <stdio.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> #include <sys/shm.h> #define MSG_SIZE 30 int main(int argc, char *argv[]) { /* two semaphores in a set index 0 - incremented when producer has reset buffer - tested and decremented by consumer to check if buffer has been reset index 1 - incremented when consumer has read buffer - tested and decremented by producer to check if consumer is done. */ 99

100 예제프로그램 #8 (6) key_t key; static struct sembuf wait_produced = { 0, -1, 0; static struct sembuf signal_consumed = { 1, 1, 0; int semid, shmid; char *message; int rtn; if((key = ftok(getenv("home"), 'u')) == (key_t) -1) { fprintf(stderr,"ftok key formation error\n"); exit(1); /* either producer or consumer might be the creator but producer will be the remover of IPC resources. producer and consumer's effective uid must be the same. */ semid = semget(key, 2, IPC_CREAT 0660); if(semid == -1) { perror("producer semget():"); exit(2); 100

101 예제프로그램 #8 (7) shmid = shmget(key, MSG_SIZE, IPC_CREAT 0660); if(semid == -1) { perror("producer shmget():"); exit(3); message = shmat(shmid, (char *) 0, SHM_RDONLY); while(1) { rtn = semop(semid, &wait_produced, 1); /* when producer is done semid will be IPC_RMID forcing break */ if(rtn == -1) { perror("consumer - semop on wait_consumed"); break; printf("%s recevied: %s\n", argv[0], message); semop(semid, &signal_consumed, 1); shmdt(message); 101

고급 IPC 설비

고급 IPC 설비 고급프로세스갂통싞 #2 세마포어 네델란드의 E.W.Dijikstra 가프로세스동기화문제의해결방안으로제시 p( ) 또는 wait( ) if (sem!= 0) decrement sem by 1 else v( ) 또는 signal( ) wait until sem become non-zero, then decrement increment sem by one if (queue

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

메시지큐를이용한 IPC 프로그램구현과제보고서 1. 과제의목적 1 리눅스가지원하는프로세스간통신방식중다수의프로세스사이에구조화된데이터블럭, 즉메시지를전달하는데주로사용되는메시지큐방식에대하여무엇인지, 어떻게사용하는지공부한다. 2 공부한내용을점검하기위해기작성된 epda 프로세스관

메시지큐를이용한 IPC 프로그램구현과제보고서 1. 과제의목적 1 리눅스가지원하는프로세스간통신방식중다수의프로세스사이에구조화된데이터블럭, 즉메시지를전달하는데주로사용되는메시지큐방식에대하여무엇인지, 어떻게사용하는지공부한다. 2 공부한내용을점검하기위해기작성된 epda 프로세스관 [ R E P O R T ] 정보통신공학전공 200301582 김성태 메시지큐를이용한 IPC 프로그램구현과제보고서 1. 과제의목적 1 리눅스가지원하는프로세스간통신방식중다수의프로세스사이에구조화된데이터블럭, 즉메시지를전달하는데주로사용되는메시지큐방식에대하여무엇인지, 어떻게사용하는지공부한다. 2 공부한내용을점검하기위해기작성된 epda 프로세스관리프로그램과 sms 메시지전송에뮬레이션프로그램을활용하여

More information

제1장 Unix란 무엇인가?

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

More information

<4D F736F F F696E74202D FBDC3BDBAC5DB56C0C720C7C1B7CEBCBCBDBAB0A320C5EBBDC5205BC8A3C8AF20B8F0B5E55D>

<4D F736F F F696E74202D FBDC3BDBAC5DB56C0C720C7C1B7CEBCBCBDBAB0A320C5EBBDC5205BC8A3C8AF20B8F0B5E55D> 학습목표 유닉스시스템V에서제공하는 IPC기법을이해한다. 메시지큐를이용해통신프로그램을작성할수있다. 공유메모리를이용해통신프로그램을작성할수있다. 세마포어를이용한 IPC기법을배운다. 시스템 V 의프로세스간통신 IT CookBook, 유닉스시스템프로그래밍 2/42 목차 시스템 V IPC 기초 시스템 V IPC 관련명령 메시지큐 공유메모리 세마포어 시스템 V IPC 기초

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

2009년 상반기 사업계획

2009년 상반기 사업계획 시스템 V 의프로세스간통신 IT CookBook, 유닉스시스템프로그래밍 학습목표 유닉스시스템V에서제공하는 IPC기법을이해한다. 메시지큐를이용해통신프로그램을작성할수있다. 공유메모리를이용해통신프로그램을작성할수있다. 세마포어를이용한 IPC기법을배운다. 2/42 목차 시스템 V IPC 기초 시스템 V IPC 관련명령 메시지큐 공유메모리 세마포어 3/42 시스템 V

More information

고급 IPC 설비

고급 IPC 설비 고급프로세스갂통싞 #1 Record Locking 여러프로세스가동시에한파일에접근하는경우경주상황 (race condition) 이발생할수있음 한가지해결방안 : Record locking 파일의일부분을잠그는행위 fcntl 을이용 #include Int fcntl(int filedes, int cmd, struct flock* ldata); cmd

More information

Microsoft PowerPoint - UnixNetProg3rd_08_완.ppt [호환 모드]

Microsoft PowerPoint - UnixNetProg3rd_08_완.ppt [호환 모드] 8. 프로세스간통신 IPC(Inter Process Communication) 은멀티프로세스로구현된서버에서프로세스간에데이터를전달하는데사용 IPC 기술 파이프, 메시지큐, 세마포어, 공유메모리 1 8.1 파이프 2 파이프 (PIPE) 운영체제가제공하는프로세스간통신채널로서특별한타입의파일 일반파일과달리메모리에저장되지않고운영체제가관리하는임시파일 데이터저장용이아닌프로세스간데이터전달용으로사용

More information

운영체제 실습 - Introduction -

운영체제 실습 - Introduction - 운영체제실습 - IPC(InterProcess Communication) - Real-Time Computing and Communications Lab. Hanyang University jtlim@rtcc.hanyang.ac.kr dhchoi@rtcc.hanyang.ac.kr beespjh@gmail.com Introduction 조교소개 이름 : 임정택

More information

제1장 Unix란 무엇인가?

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

More information

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

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

More information

제12장 파일 입출력

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

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

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

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

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

<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

10주차.key

10주차.key 10, Process synchronization (concurrently) ( ) => critical section ( ) / =>, A, B / Race condition int counter; Process A { counter++; } Process B { counter ;.. } counter++ register1 = counter register1

More information

슬라이드 1

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

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

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

좀비프로세스 2

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

More information

vi 사용법

vi 사용법 네트워크프로그래밍 6 장과제샘플코드 - 1:1 채팅 (udp 버전 ) 과제 서버에서먼저 bind 하고그포트를다른사람에게알려줄것 클라이언트에서알려준포트로접속 서로간에키보드입력을받아상대방에게메시지전송 2 Makefile 1 SRC_DIR =../../common 2 COM_OBJS = $(SRC_DIR)/addressUtility.o $(SRC_DIR)/dieWithMessage.o

More information

2009년 상반기 사업계획

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

More information

슬라이드 1

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

More information

< E20C6DFBFFEBEEE20C0DBBCBAC0BB20C0A7C7D12043BEF0BEEE20492E707074>

< E20C6DFBFFEBEEE20C0DBBCBAC0BB20C0A7C7D12043BEF0BEEE20492E707074> Chap #2 펌웨어작성을위한 C 언어 I http://www.smartdisplay.co.kr 강의계획 Chap1. 강의계획및디지털논리이론 Chap2. 펌웨어작성을위한 C 언어 I Chap3. 펌웨어작성을위한 C 언어 II Chap4. AT89S52 메모리구조 Chap5. SD-52 보드구성과코드메모리프로그래밍방법 Chap6. 어드레스디코딩 ( 매핑 ) 과어셈블리어코딩방법

More information

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

[ 마이크로프로세서 1] 2 주차 3 차시. 포인터와구조체 2 주차 3 차시포인터와구조체 학습목표 1. C 언어에서가장어려운포인터와구조체를설명할수있다. 2. Call By Value 와 Call By Reference 를구분할수있다. 학습내용 1 : 함수 (Functi 2 주차 3 차시포인터와구조체 학습목표 1. C 언어에서가장어려운포인터와구조체를설명할수있다. 2. Call By Value 와 Call By Reference 를구분할수있다. 학습내용 1 : 함수 (Function) 1. 함수의개념 입력에대해적절한출력을발생시켜주는것 내가 ( 프로그래머 ) 작성한명령문을연산, 처리, 실행해주는부분 ( 모듈 ) 자체적으로실행되지않으며,

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

Abstract View of System Components

Abstract View of System Components Operating System 10 주차 - IPC(InterProcess Communication) - Real-Time Computing and Communications Lab. Hanyang University jtlim@rtcc.hanyang.ac.kr yschoi@rtcc.hanyang.ac.kr shpark@rtcc.hanyang.ac.kr Contents

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

11장 포인터

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

More information

The Pocket Guide to TCP/IP Sockets: C Version

The Pocket Guide to  TCP/IP Sockets: C Version 1 목포해양대해양컴퓨터공학과 UDP 소켓 네트워크프로그램설계 4 장 2 목포해양대해양컴퓨터공학과 목차 제 4장 UDP 소켓 4.1 UDP 클라이언트 4.2 UDP 서버 4.3 UDP 소켓을이용한데이터송신및수신 4.4 UDP 소켓의연결 3 목포해양대해양컴퓨터공학과 UDP 소켓의특징 UDP 소켓의특성 신뢰할수없는데이터전송방식 목적지에정확하게전송된다는보장이없음.

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

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

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

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

슬라이드 1

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

More information

<4D F736F F F696E74202D FB8DEB8F0B8AE20B8C5C7CE205BC8A3C8AF20B8F0B5E55D>

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

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

2009년 상반기 사업계획

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

More information

제9장 프로세스 제어

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

More information

03장.스택.key

03장.스택.key ---------------- DATA STRUCTURES USING C ---------------- 03CHAPTER 1 ? (stack): (LIFO:Last-In First-Out) 2 : top : ( index -1 ),,, 3 : ( ) ( ) -> ->. ->.... 4 Stack ADT : (LIFO) : init():. is_empty():

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

입학사정관제도

입학사정관제도 운영체제 강의노트 교재 : 운영체제 ( 개정판 ) 출판사 : 한빛미디어 (2010 년 11 월발행 ) 저자 : 구현회 소프트웨어학과원성현교수 1 4 장 병행프로세스와 상호배제 소프트웨어학과원성현교수 2 1. 병행프로세스 병행프로세스의과제 병행성 동시에 2 개이상의프로세스가실행되는성질 다중프로세싱시스템, 분산처리시스템에서주로발생 다중프로세싱시스템은프로세서의효율성을증대시킴

More information

PowerPoint 프레젠테이션

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

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 프레젠테이션 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

À©µµ³×Æ®¿÷ÇÁ·Î±×·¡¹Ö4Àå_ÃÖÁ¾

À©µµ³×Æ®¿÷ÇÁ·Î±×·¡¹Ö4Àå_ÃÖÁ¾ P a 02 r t Chapter 4 TCP Chapter 5 Chapter 6 UDP Chapter 7 Chapter 8 GUI C h a p t e r 04 TCP 1 3 1 2 3 TCP TCP TCP [ 4 2] listen connect send accept recv send recv [ 4 1] PC Internet Explorer HTTP HTTP

More information

Microsoft Word - Network Programming_NewVersion_01_.docx

Microsoft Word - Network Programming_NewVersion_01_.docx 10. Unix Domain Socket 105/113 10. Unix Domain Socket 본절에서는 Unix Domain Socket(UDS) 에대한개념과이에대한실습을수행하고, 이와동시에비신뢰적인통신시스템의문제점에대해서분석하도록한다. 이번실습의목표는다음과같다. 1. Unix Domain Socket의사용법을익히고, IPC에대해서실습 2. TCP/IP의응용계층과전달계층의동작을구현및실습

More information

제1장 Unix란 무엇인가?

제1장  Unix란 무엇인가? 1 소켓 2 1 소켓 클라이언트 - 서버모델 네트워크응용프로그램 클리이언트 - 서버모델을기반으로동작한다. 클라이언트 - 서버모델 하나의서버프로세스와여러개의클라이언트로구성된다. 서버는어떤자원을관리하고클라이언트를위해자원관련서비스를제공한다. 3 소켓의종류 소켓 네트워크에대한사용자수준의인터페이스를제공 소켓은양방향통신방법으로클라이언트 - 서버모델을기반으로프로세스사이의통신에매우적합하다.

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 PowerPoint - ch07 - 포인터 pm0415

Microsoft PowerPoint - ch07 - 포인터 pm0415 2015-1 프로그래밍언어 7. 포인터 (Pointer), 동적메모리할당 2015 년 4 월 4 일 교수김영탁 영남대학교공과대학정보통신공학과 (Tel : +82-53-810-2497; Fax : +82-53-810-4742 http://antl.yu.ac.kr/; E-mail : ytkim@yu.ac.kr) Outline 포인터 (pointer) 란? 간접참조연산자

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

이번장에서학습할내용 동적메모리란? 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

K&R2 Reference Manual 번역본

K&R2 Reference Manual 번역본 typewriter structunion struct union if-else if if else if if else if if if if else else ; auto register static extern typedef void char short int long float double signed unsigned const volatile { } struct

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

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

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

<322EBCF8C8AF28BFACBDC0B9AEC1A6292E687770>

<322EBCF8C8AF28BFACBDC0B9AEC1A6292E687770> 연습문제해답 5 4 3 2 1 0 함수의반환값 =15 5 4 3 2 1 0 함수의반환값 =95 10 7 4 1-2 함수의반환값 =3 1 2 3 4 5 연습문제해답 1. C 언어에서의배열에대하여다음중맞는것은? (1) 3차원이상의배열은불가능하다. (2) 배열의이름은포인터와같은역할을한다. (3) 배열의인덱스는 1에서부터시작한다. (4) 선언한다음, 실행도중에배열의크기를변경하는것이가능하다.

More information

슬라이드 1

슬라이드 1 CHAP 6: 큐 yicho@gachon.ac.kr 1 큐 (QUEUE) 큐 : 먼저들어온데이터가먼저나가는자료구조 선입선출 (FIFO: First-In First-Out) ( 예 ) 매표소의대기열 Ticket Box 전단 () 후단 () 2 큐 ADT 삽입과삭제는 FIFO 순서를따른다. 삽입은큐의후단에서, 삭제는전단에서이루어진다. 객체 : n 개의 element

More information

슬라이드 1

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

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

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

Microsoft PowerPoint - Lecture_Note_5.ppt [Compatibility Mode]

Microsoft PowerPoint - Lecture_Note_5.ppt [Compatibility Mode] TCP Server/Client Department of Computer Engineering Kyung Hee University. Choong Seon Hong 1 TCP Server Program Procedure TCP Server socket() bind() 소켓생성 소켓번호와소켓주소의결합 listen() accept() read() 서비스처리, write()

More information

Microsoft PowerPoint - chap11-포인터의활용.pptx

Microsoft PowerPoint - chap11-포인터의활용.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

본 강의에 들어가기 전

본 강의에 들어가기 전 C 기초특강 종합과제 과제내용 구조체를이용하여교과목이름과코드를파일로부터입력받아관리 구조체를이용하여학생들의이름, 학번과이수한교과목의코드와점수를파일로부터입력 학생개인별총점, 평균계산 교과목별이수학생수, 총점및평균을계산 결과를파일에저장하는프로그램을작성 2 Makefile OBJS = score_main.o score_input.o score_calc.o score_print.o

More information

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

목차 포인터의개요 배열과포인터 포인터의구조 실무응용예제 C 2 제 8 장. 포인터 목차 포인터의개요 배열과포인터 포인터의구조 실무응용예제 C 2 포인터의개요 포인터란? 주소를변수로다루기위한주소변수 메모리의기억공간을변수로써사용하는것 포인터변수란데이터변수가저장되는주소의값을 변수로취급하기위한변수 C 3 포인터의개요 포인터변수및초기화 * 변수데이터의데이터형과같은데이터형을포인터 변수의데이터형으로선언 일반변수와포인터변수를구별하기위해

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

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

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 @ Lesson 3 if, if else, if else if, switch case for, while, do while break, continue : System.in, args, JOptionPane for (,, ) @ vs. logic data method variable Data Data Flow (Type), ( ) @ Member field

More information

Microsoft PowerPoint - 13 ¼ÒÄÏÀ» ÀÌ¿ëÇÑ Åë½Å 2.ppt

Microsoft PowerPoint - 13 ¼ÒÄÏÀ» ÀÌ¿ëÇÑ Åë½Å 2.ppt 13 장소켓을이용한통신 (2) 소켓을이용한통신 (2) 함수 - recvfrom - sendto - uname - gethostname - gethostbyname - gethostbyaddr 1 1. 서론 소켓을사용하여비연결형모델로통신을하기위한함수와그외의함수 함수 의미 recvfrom 비연결형모델에서소켓을통해메시지를수신한다. sendto 비연결형모델에서소켓을통해메시지를송신한다.

More information

슬라이드 1

슬라이드 1 CHP 6: 큐 C 로쉽게풀어쓴자료구조 생능출판사 2005 큐 (QUEUE) 큐 : 먼저들어온데이터가먼저나가는자료구조 선입선출 (FIFO: First-In First-Out) ( 예 ) 매표소의대기열 Ticket Box 전단 () 후단 () 큐 DT 삽입과삭제는 FIFO 순서를따른다. 삽입은큐의후단에서, 삭제는전단에서이루어진다. 객체 : n 개의 element

More information

C++-¿Ïº®Çؼ³10Àå

C++-¿Ïº®Çؼ³10Àå C C++. (preprocessor directives), C C++ C/C++... C++, C. C++ C. C C++. C,, C++, C++., C++.,.. #define #elif #else #error #if #itdef #ifndef #include #line #pragma #undef #.,.,. #include #include

More information

리눅스 프로세스 관리

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

More information

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

Microsoft PowerPoint - ch10 - 이진트리, AVL 트리, 트리 응용 pm0600 균형이진탐색트리 -VL Tree delson, Velskii, Landis에의해 1962년에제안됨 VL trees are balanced n VL Tree is a binary search tree such that for every internal node v of T, the heights of the children of v can differ by at

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

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

3. 다음장에나오는 sigprocmask 함수의설명을참고하여다음프로그램의출력물과그출력물이화면이표시되는시점을예측하세요. ( 힌트 : 각줄이표시되는시점은다음 4 가지중하나. (1) 프로그램수행직후, (2) kill 명령실행직후, (3) 15 #include <signal. 학번 : 이름 : 1. 다음가정하에서아래프로그램의출력물을예측하세요. 가정 : 부모프로세스의 process id=20100, 자식프로세스의 process id=20101. int glob = 31; /* external variable in initialized data */ char buf[] = "a write to stdout\n"; int main(void)

More information

학습목차 2.1 다차원배열이란 차원배열의주소와값의참조

학습목차 2.1 다차원배열이란 차원배열의주소와값의참조 - Part2- 제 2 장다차원배열이란무엇인가 학습목차 2.1 다차원배열이란 2. 2 2 차원배열의주소와값의참조 2.1 다차원배열이란 2.1 다차원배열이란 (1/14) 다차원배열 : 2 차원이상의배열을의미 1 차원배열과다차원배열의비교 1 차원배열 int array [12] 행 2 차원배열 int array [4][3] 행 열 3 차원배열 int array [2][2][3]

More information

BMP 파일 처리

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

More information

Microsoft PowerPoint - 3ÀÏ°_º¯¼ö¿Í »ó¼ö.ppt

Microsoft PowerPoint - 3ÀÏ°_º¯¼ö¿Í »ó¼ö.ppt 변수와상수 1 변수란무엇인가? 변수 : 정보 (data) 를저장하는컴퓨터내의특정위치 ( 임시저장공간 ) 메모리, register 메모리주소 101 번지 102 번지 변수의크기에따라 주로 byte 단위 메모리 2 기본적인변수형및변수의크기 변수의크기 해당컴퓨터에서는항상일정 컴퓨터마다다를수있음 short

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

Microsoft PowerPoint - 08-chap06-Queue.ppt

Microsoft PowerPoint - 08-chap06-Queue.ppt / 큐 (QUEUE) Chapter 큐 : 먼저들어온데이터가먼저나가는자료구조 선입선출 (FIFO: First-In First-Out) ( 예 ) 매표소의대기열 큐 Ticket ox Dongwon Jeong djeong@kunsan.ac.kr Department of Kunsan National University 전단 () 후단 () 학습목표 큐 DT 큐의개념및추상데이터타입에대한이해

More information

Microsoft PowerPoint - StallingsOS6e-Chap05.pptx

Microsoft PowerPoint - StallingsOS6e-Chap05.pptx 5 장병행성 : 상호배제와동기화 5 장의강의목표 병행성 (concurrency) 의원리와주요용어를이해한다. 경쟁상태 (race condition) 의문제점에대해이해한다. 상호배제 (mutual exclusion), 교착상태 (deadlock), 기아상태 (starvation) 의 3 가지제어문제를이해한다. 상호배제를보장하기위한하드웨어적접근방법을이해한다. 세마포어를이용한상호배제기법을이해한다.

More information

Microsoft PowerPoint - chap03-변수와데이터형.pptx

Microsoft PowerPoint - chap03-변수와데이터형.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

<4D F736F F F696E74202D20C1A63137C0E520B5BFC0FBB8DEB8F0B8AEBFCD20BFACB0E1B8AEBDBAC6AE>

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

More information

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션 Chapter 06 반복문 01 반복문의필요성 02 for문 03 while문 04 do~while문 05 기타제어문 반복문의의미와필요성을이해한다. 대표적인반복문인 for 문, while 문, do~while 문의작성법을 알아본다. 1.1 반복문의필요성 반복문 동일한내용을반복하거나일정한규칙으로반복하는일을수행할때사용 프로그램을좀더간결하고실제적으로작성할수있음.

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 - 제11장 포인터(강의)

Microsoft PowerPoint - 제11장 포인터(강의) 쉽게풀어쓴 C 언어 Express 제 11 장포인터 이번장에서학습할내용 포인터이란? 변수의주소 포인터의선언 간접참조연산자 포인터연산 포인터와배열 포인터와함수 이번장에서는포인터의기초적인지식을학습한다. 포인터란? 포인터 (pointer): 주소를가지고있는변수 1003 1004 1005 영화관 1002 1006 1001 포인터 (pointer) 1007 메모리의구조

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

비트와바이트 비트와바이트 비트 (Bit) : 2진수값하나 (0 또는 1) 를저장할수있는최소메모리공간 1비트 2비트 3비트... n비트 2^1 = 2개 2^2 = 4개 2^3 = 8개... 2^n 개 1 바이트는 8 비트 2 2

비트와바이트 비트와바이트 비트 (Bit) : 2진수값하나 (0 또는 1) 를저장할수있는최소메모리공간 1비트 2비트 3비트... n비트 2^1 = 2개 2^2 = 4개 2^3 = 8개... 2^n 개 1 바이트는 8 비트 2 2 비트연산자 1 1 비트와바이트 비트와바이트 비트 (Bit) : 2진수값하나 (0 또는 1) 를저장할수있는최소메모리공간 1비트 2비트 3비트... n비트 2^1 = 2개 2^2 = 4개 2^3 = 8개... 2^n 개 1 바이트는 8 비트 2 2 진수법! 2, 10, 16, 8! 2 : 0~1 ( )! 10 : 0~9 ( )! 16 : 0~9, 9 a, b,

More information

untitled

untitled while do-while for break continue while( ) ; #include 0 i int main(void) int meter; int i = 0; while(i < 3) meter = i * 1609; printf("%d %d \n", i, meter); i++; return 0; i i< 3 () 0 (1)

More information

Microsoft PowerPoint - chap12 [호환 모드]

Microsoft PowerPoint - chap12 [호환 모드] 제 12 장고급입출력 Nov 2007 숙대창병모 1 Contents 1. Nonblocking I/O 2. Record Locking 3. Memory Mapped I/O Nov 2007 숙대창병모 2 12.1 Nonblocking I/O Nov 2007 숙대창병모 3 Nonblocking I/O Blocking I/O I/O 작업완료를기다리며영원히리턴안할수있다

More information

untitled

untitled if( ) ; if( sales > 2000 ) bonus = 200; if( score >= 60 ) printf(".\n"); if( height >= 130 && age >= 10 ) printf(".\n"); if ( temperature < 0 ) printf(".\n"); // printf(" %.\n \n", temperature); // if(

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 - 08-Queue.ppt

Microsoft PowerPoint - 08-Queue.ppt Chapter Queue ( 큐 ) Dongwon Jeong djeong@kunsan.ac.kr Department of Informatics & Statistics 학습목표 큐의개념및추상데이터타입에대한이해 큐의구현방법 배열 링크드리스트 덱 / 데크의개념과구현방법 큐 (QUEUE) 큐 : 먼저들어온데이터가먼저나가는자료구조 선입선출 (FIFO: First-In

More information

歯9장.PDF

歯9장.PDF 9 Hello!! C printf() scanf() getchar() putchar() gets() puts() fopen() fclose() fprintf() fscant() fgetc() fputs() fgets() gputs() fread() fwrite() fseek() ftell() I/O 2 (stream) C (text stream) : `/n'

More information