Presentation is loading. Please wait.

Presentation is loading. Please wait.

제2부 프로세스 관리 (Process Management)

Similar presentations


Presentation on theme: "제2부 프로세스 관리 (Process Management)"— Presentation transcript:

1 제2부 프로세스 관리 (Process Management)
실행중인 프로그램(program in execution) CPU time, memory, files, I/O devices 등 자원 요구 시스템의 작업단위 (the unit of work) 종류 1. 사용자 프로세스(user process) - user code 실행 2. 시스템 프로세스(system process) - system code 실행 프로세스 관리 사용자 프로세스와 시스템 프로세스의 생성과 삭제 프로세스 스케줄링 프로세스들의 동기화 기법 지원 프로세스들의 통신 지원 프로세스들의 교착상태(deadlock)처리 운영체제

2 Chapter 3. 프로세스 개념(Process Concept)
Questions of the day 프로세스는 □ □ 중인 프로그램? Linux 는 프로세스를 표현하는 PCB(Process Control Block) 구조체 이름은? Unix/Linux 프로세스를 생성하는 시스템 호출은? 프로세스 스케줄링이 사용하는 큐는? 프로세스의 문맥(context)은 어디에 저장? 컴퓨터 시스템 안에서 발견할 수 있는 생산자-소비자 관계에 있는 프로세스들의 예는? 유한 버퍼 생산자-소비자 문제 (bounded buffer producer-consumer problem) 해결책은? 운영체제

3 프로세스 개념(Process Concept)
예전 1 program 실행  오늘날 multiple program의 동시 실행 프로세스 (The Process) 프로그램 코드 + 현재 활동(Current activity) PC(Program Counter) 레지스터 값 스택(stack) : 서브루틴, 매개변수, 복귀주소, 임시변수 등 데이터 부분(data section) : 전역변수 프로세스 상태(Process State) 생성(new) 수행(running) : CPU가 실행 대기(waiting) : I/O완료나 signal 기다림 준비(ready) : Processor를 받을 준비가 됨 종료(terminated) 운영체제

4 Process in Memory

5 프로세스 상태(Process State)
운영체제

6 BSS(Block Started by Symbol)
(참고) Linux 가상 메모리 구조 하나의 태스크마다 4GB 주소 공간을 할당 각 태스크에게 3GB 할당 나머지 1GB는 모든 태스크들의 공통 영역으로서 커널 공간으로 할당 $ cat /proc/1/maps BSS(Block Started by Symbol) 운영체제

7 (참고) Linux 메모리 관리 자료구조 task_struct 구조체내의 struct mm_struct *mm
/usr/src/kernels/linux /include/linux/sched.h (1256행 Fedora Linux ) /usr/src/kernels/linux /include/linux/mm_types.h (222행, 131행) 메모리 디스크립터 운영체제

8 프로세스 개념(Process Concept)
프로세스 제어 블럭(Process Control Block)  /proc 참고 각 프로세스는 PCB로 표현됨 Solaris 10 Unix: /usr/include/sys/proc.h (99행) Fedora Linux: /usr/src/kernels/linux /include/linux/sched.h (1193행) PCB 프로세스 상태: new, ready, running, waiting, halted 프로그램 카운터: next instruction의 주소 CPU레지스터들: accumulator, index register, stack pointers, 범용 registers, condition-code CPU스케줄 정보: priority, pointers to scheduling queues 메모리 관리 정보: base and limit registers, page tables, segment tables 계정 정보: time used, time limits, account numbers, job#, process# 입출력 상태 정보: I/O devices list allocated to the process, list of open files 스레드(Threads) a process = a single thread of execution (one task) 많은 현대 OS들이 multiple threads of control (multitasks at a time) 지원 운영체제

9 Process Control Block (PCB)
운영체제

10 Linux task_struct 구조체 구조체를 통한 정보 관리
모든 태스크들에게 하나씩 할당 /usr/src/kernels/linux /include/linux/sched.h (1193행) 태스크 ID, 상태 정보, 가족 관계, 명령, 데이터, 시그널, 우선순위, CPU 사용량 및 파일 디스크립터 등 생성된 태스크의 모든 정보를 가짐 alloc_task_struct 매크로를 통해 커널 영역의 메모리에서 8KB를 할당받아 프로세스 디스크립터와 커널 스택의 자료를 저장 current :현재 실행되고 있는 태스크를 가리키는 변수 /usr/src/kernels/inux /arch/x86/include/asm/current.h (17행) 커널 스택과 프로세스 디스크립터 운영체제

11 Linux task_struct 구조체 태스크 관계와 관련된 변수들 p_opptr과 p_pptr : 부모 태스크 p_oppr : Original Parent p_cptr : 자식, p_ysptr : 아우, p_osptr : 형 커널에 존재하는 모든 태스크들은 원형 이중 연결 리스트로 연결 SET_LINKS : 리스트에 추가하는 매크로 REMOVE_LINK : 리스트서 삭제하는 매크로 struct task_struct *p_opptr, *p_pptr, *p_cptr, *p_ysptr, *p_osptr; struct task_struct *next_task, *prev_task; task_struct 구조체 운영체제

12 프로세스 스케줄링(Process Scheduling)
스케줄링 큐(Scheduling Queues) 작업 큐 (job queue) : memory 할당 기다리는 큐(disk에서) 준비 큐 (ready queue) : CPU에 할당 기다리는 큐 장치 큐 (device queue() : 입출력 기다리는 큐 큐잉 도표 (queueing diagram) : 그림 3.7 스케줄러(Schedulers) 장기 스케줄러(long-term scheduler, job scheduler) pool  memory(degree of multiprogramming) Unix 같은 시분할 시스템에는 없음 단기 스케줄러(short-term scheduler, CPU scheduler) CPU 할당 : must be very fast 중기 스케줄러(medium-term scheduler) swapping degree of multiprogramming을 줄임 memory  backing store 운영체제

13 준비큐와 다양한 입출력 장치 큐 운영체제

14 프로세스 스케줄링을 표현하는 큐잉 도표 운영체제

15 큐잉 도표에 중기 스케줄링(Medium Term Scheduling) 추가
운영체제

16 프로세스 스케줄링(Process Scheduling)
문맥 교환(Context Switch) CPU가 한 process에서 다른 process로 switch될 때 save the state of the old process : CPU와 메모리 상태(PCB정보) load the saved state for new process : CPU와 메모리 상태(PCB정보) pure overhead : performance bottleneck  threads로 해결 context-switch time : microsecond address space 보존 방법 : memory 관리기법에 좌우 운영체제

17 한 프로세스에서 다른 프로세스로의 CPU Switch
운영체제

18 프로세스에 대한 오퍼레이션(Operations on Processes)
프로세스 생성(Process Creation) 프로세스 생성 시스템 호출 : fork, exec, CreateProcess, etc. 부모 프로세스 자신 프로세스 : 사용 자원을 부모 프로세스의 자원(memory, files) 공유 새 프로세스 생성 후 부모는 계속 실행 모든 자식이 끝날 때 까지 기다림 : wait system call로 운영체제

19 전형적인 UNIX System의 프로세스 트리
$ ps –ef | more $ ps ax | more 운영체제

20 A tree of processes on a typical Solaris
Q: Linux의 1번 프로세스는? 운영체제

21 프로세스에 대한 오퍼레이션(Operations on Processes)
새 프로세스의 2모델 (자식의 주소 공간 관점에서 본) 1) 자식은 부모의 것을 복제 : fork 2) 자식은 자신의 새 프로그램을 가짐 : fork+exec군 Unix의 예 : fork + exec 프로그램 (forkexecl.c & forkexecv.c 참조) 1) fork : 자식 process 생성, 모든 process는 PID(Process identifier)를 가짐 2) fork + exec : 호출하는 프로세스의 기억장소에 새 프로그램 load execl : 문자형 인수 포인터들 execl(“/bin/ls”, “ls”, “-l”, NULL); execv : 인수배열의 포인터 char *av[3]; av[0] = “ls”; av[1] = “-l”; av[2] = (char *)0; execv(“/bin/ls”, av); 운영체제

22 프로세스에 대한 오퍼레이션(Operations on Processes)
프로세스 종료(Process Termination) exit 시스템 종료 계산 결과는 부모에게 Return 메모리(물리적/가상적), 오픈한 화일, I/O버퍼를 OS에게 돌려줌 abort 시스템 호출 부모만 호출(그렇지 않으면 서로 죽이는 일 생김) 실행 종료 이유 자식이 할당된 자원을 초과 사용할 때 자식의 task가 더 이상 필요 없을 때 부모가 종료될 때 DEC VMS 또는 Unix 계단식(cascading) 종료 부모 종료  OS가 모든 자식 종료 (예) Unix (mystatus.c 참조) exit system call로 프로세스 종료 wait system call : return값 = 종료하는 자식의 pid wait(&status) /* int status */ status :자식이 exit으로 종료될 때의 상태정보 정상종료 경우 : 하위 8bits는 0, 상위 8bits 는 exit status(자식 프로세스가 exit 명령으로 전달한 값), signal로 종료된 경우 : 하위 8bits는 signal 번호, 상위 8bits는 0 (상위 8 비트 추출) status >> 8; status &= 0xFF; 운영체제

23 Lab 3. 프로세스 생성과 종료 (Unix/Linux) One, Two 출력하는 onetwo.c 코딩, 컴파일, 실행
(Unix/Linux) fork 예제 forkvalue.c 코딩, 컴파일, 실행 (Unix/Linux) 시스템 호출 execl()을 이용하여 ls 프로그램을 실행시키는 forkexecl.c 코딩, 컴파일, 실행 (Unix/Linux) 시스템 호출 execv()를 이용하여 ls 프로그램을 실행시키는 forkexecv.c 코딩, 컴파일, 실행 (Unix/Linux) Shell을 느끼는 background.c 코드 분석, 컴파일, 실행 (Unix/Linux) mystatus.c & myexit.c 코드 분석, 컴파일, 실행 (Windows) Win32 API를 이용한 새 프로세스 생성 (교재 p108) 코딩, 컴파일, 실행 1~6번만 제출 (집에서도 접속 가능합니다) 2 Electronic versions: multi.incheon.ac.kr ( )의 지정 디렉토리 /export/home/os2011hwa 또는 os2011hwb 에 자기 학번의 디렉토리 만들고 그 곳에 소스파일과 실행파일 복사 mylinux.incheon.ac.kr ( ) 지정 디렉토리 /home/os2011hwa 또는 os2011hwb 에 자기 학번의 디렉토리 만들고 그 곳에 소스파일과 실행파일 복사 운영체제

24 1. fork 시스템 호출: onetwo.c printf(“One\n”); pid = fork();
#include <stdio.h> main() { int pid; printf("One\n"); pid = fork(); printf("Two\n"); } printf(“One\n”); pid = fork(); printf(Two\n”); PC A $ gcc onetwo.c –o onetwo BEFORE fork AFTER printf(“One\n”); pid=fork(); printf(“Two\n”); printf(“One\n”); pid = fork(); printf(“Two\n”); PC PC A B 운영체제

25 2. fork() 예제 forkvalue.c #include <stdio.h> int value = 5;
main () { int pid; pid = fork (); /* Duplicate. Child and parent continue from here */ if (pid != 0) /* pid is non-zero, so I must be the parent */ wait(NULL); printf ("Parent: value = %d\n", value); } else /* pid is zero, so I must be the child */ value += 15; printf ("Child: value = %d\n", value); printf ("PID %d terminates.\n", getpid () ); /* Both processes execute this */ 운영체제

26 3. fork와 exec호출의 조합 pid = fork(); execl(“/bin/ls” …); wait((int*)0);
PC A BEFORE FORK AFTER FORK wait((int*)0); execl(“/bin/ls” …); PC PC A B AFTER FORK AFTER EXEC wait((int*)0); /* first line of ls */ PC PC A B (now runs ls) 운영체제

27 3.&4. fork()로 새 프로세스를 생성하는 C program
#include <stdio.h> #include <stdlib.h> #include <unistd.h> void main(int argc, char *argv[]) { int pid; /* fork another process */ pid = fork(); if(pid < 0) { /* error occurred */ fprintf(stderr, “Fork Failed”); exit(-1); } else if (pid == 0) { /* child process */ execl(“/bin/ls”, “ls”, “-l”, NULL); } else { /* parent process */ wait(NULL); printf(“Child Complete\n”); exit(0); } execv char *av[3]; av[0]=“ls”; av[1]=“-l”; av[2]=(char *)0; execv(“/bin/ls”, av); execlp, execvp 쉘 환경변수 PATH를 따름 execlp(“ls”, “ls”, “-l”, (char *)0); execvp(“ls”, av); 운영체제

28 5. Shell을 느끼는 background.c
후면처리 (background processing) 실행 $ gcc background.c –o background $ ./background ls -l 코드 $ cat background.c #include <stdio.h> main (argc, argv) int argc; char* argv []; { if (fork () == 0) /* Child */ execvp (argv[1], &argv[1]); /* Execute other program */ fprintf (stderr, "Could not execute %s\n", argv[1]); } 운영체제

29 6. exit 예제 mystatus.c & myexit.c
$ cat mystatus.c #include <stdio.h> #include <stdlib.h> #include <unistd.h> main () { int pid, status, childPid; printf ("I'm the parent process and my PID is %d\n", getpid ()); pid = fork (); /* Duplicate */ if (pid != 0) /* Branch based on return value from fork () */ printf ("I'm the parent process with PID %d and PPID %d\n", getpid (), getppid ()); childPid = wait (&status); /* Wait for a child to terminate. */ printf ("A child with PID %d, terminated with exit code low: %d, high: %d\n", childPid, (status & 0xFF), status >> 8); /* Linux */ } else printf ("I'm the child process with PID %d and PPID %d\n", getpid (), getppid ()); execlp ("ls", "ls", "-li", (char *)0); /* execlp ("myexit", "myexit", (char *)0); */ exit (42); /* Exit with a silly number */ printf ("PID %d terminates\n", getpid () ); $ cat myexit.c #include <stdio.h> #include <stdlib.h> main () { printf ("I'm going to exit with return code 33\n"); exit (33); } 운영체제

30 7. Win32 API를 이용한 새 프로세스 생성 실행오류나면 Visual Studio의 프로젝트 속성일반문자집합
#include <Windows.h> #include <stdio.h> int main(void) { STARTUPINFO si; PROCESS_INFORMATION pi; ZeroMemory( &si, sizeof(si) ); si.cb = sizeof(si); ZeroMemory( &pi, sizeof(pi) ); if(!CreateProcess(NULL, // 명령어라인사용 "C://Windows/System32//mspaint.exe", // 명령어라인 NULL, // 프로세스를상속하지말것 NULL, // 쓰레드핸들을상속하지말것 FALSE, // 핸들상속다제이블 0, // 생성플래그없음 NULL, // 부모환경블록사용 NULL, // 부모프로세스가존재하는디렉토리사용 &si, &pi)) fprintf(stderr, "Create Process Failed"); return -1; } // 부모프로세스가자식프로세스가끝나기를기다림 WaitForSingleObject(pi.hProcess, INFINITE); printf("Child Complete"); // 핸들닫기 CloseHandle(pi.hProcess); CloseHandle(pi.hThread); 실행오류나면 Visual Studio의 프로젝트 속성일반문자집합 을 [멀티바이트 문자집합 사용]으로 변경 운영체제

31 프로세스 협조(Cooperating Processes)
프로세스 협조하는 이유 정보 공유 (information sharing) 계산 속도 증가 (computation speedup) : parallel computing으로 모듈화(modularity) 편이성(convenience) : parallel computing으로 프로세스 협조 예 : 생산자-소비자(producer-consumer)문제 compiler : assembly code 생산 assembler : assembly code 소비, object code 생산 loader : object code 소비 생산자와 소비자가 동시에 수행되려면  buffer가 필요(동시 수행을 위해)  생산자와 소비자의 동기화 필요(생산되지 않은 자료 소비하지 않게) 생산자-소비자 문제 종류 1. 무한 버퍼(unbounded-buffer) 생산자-소비자 문제 생산자는 항상 생산, 소비자는 소비할 자료를 기다릴 수도 2. 유한 버퍼(bounded-buffer) 생산자-소비자 문제 버퍼가 꽉 차 있으면 생산자가 대기, 버퍼가 비어 있으면 소비자가 대기 운영체제

32 프로세스 협조(Cooperating Processes)
유한 버퍼 생산자-소비자 문제(bounded-buffer producer-consumer problem)  스레드(LWP)로 하면 효과적 Version 1: 공유 메모리를 이용한 해결책 (3.4.1절) Version 2: 메시지 전달(IPC)을 이용한 해결책 (3.4.2절) Version 3: 세마포어를 이용한 해결책 (6.6.1절) Version 4: 세마포어와 스레드를 이용한 해결책 (6장 프로젝트 p266) Version 5: Java synchronization을 이용한 해결책 운영체제

33 Shared Memory count=0 in=0 out=0 count=3 in=0 out=0 count=0 count=2
1 count=1 in=0 out=2 count=2 in=0 out=1 count=1 in=1 out=0 운영체제

34 Shared Memory count=3 count=0 in=0 in=0 out=0 out=0 count=0 count=2
count=1 in=0 out=2 count=2 in=0 out=1 1 count=1 in=1 out=0 운영체제

35 공유 메모리를 이용하는 생산자-소비자 문제 import java.util.*; public class BoundedBuffer
{ public BoundedBuffer() { // buffer is initially empty count = 0; in = 0; out = 0; buffer = new Object[BUFFER_SIZE]; } // producer calls this method public void enter(Object item) { // The enter method // consumer calls this method public Object remove() { // The remove() method public static final int NAP_TIME = 5; private static final int BUFFER_SIZE = 3; private volatile int count; private int in; // points to the next free position private int out; //points to the next full position private Object[] buffer; 운영체제

36 공유 메모리 시스템의 생산자 enter() 메소드
public void enter(Object item) { while (count == BUFFER_SIZE) ; // do nothing // add an item to the buffer ++count; buffer[in] = item; in = (in + 1) % BUFFER_SIZE; if (count == BUFFER_SIZE) System.out.printIt(“Producer Entered “ + item + “ Buffer Full”); else System.out.printIt(“Producer Entered “ + item + “ Buffer size = “ + count); } 운영체제

37 공유 메모리 시스템의 소비자 remove() 메소드
public Oject remove() { Object item; while (count == 0) ; // do nothing // remove an item to the buffer --count; item = buffer[out]; out = (out + 1) % BUFFER_SIZE; if (count == 0) System.out.printIt(“Consumer Consumed “ + item + “ BufferEmpty”); else System.out.printIt(“Consumer Consumer “ + item + “ Buffer size = “ + count); } 운영체제

38 공유 메모리 시스템의 Consumer.java
import java.util.*; public class Consumer extends Thread { public Consumer(BoundedBuffer b) buffer = b; } public void run() Date message; while (true) int sleeptime = (int) (BoundedBuffer.NAP_TIME * Math.random() ); System.out.println("Consumer sleeping for " + sleeptime + " seconds"); try { sleep(sleeptime*1000); } catch(InterruptedException e) {} // consume an item from the buffer System.out.println("Consumer wants to consume."); message = (Date)buffer.remove(); private BoundedBuffer buffer; 운영체제

39 공유 메모리 시스템의 Producer.java
import java.util.*; public class Producer extends Thread { public Producer(BoundedBuffer b) { buffer = b; } public void run() Date message; while (true) int sleeptime = (int) (BoundedBuffer.NAP_TIME * Math.random() ); System.out.println("Producer sleeping for " + sleeptime + " seconds"); try { sleep(sleeptime*1000); } catch(InterruptedException e) {} // produce an item & enter it into the buffer message = new Date(); System.out.println("Producer produced " + message); buffer.enter(message); private BoundedBuffer buffer; 운영체제

40 공유 메모리 시스템의 Server.java public class Server {
public static void main(String args[]) { BoundedBuffer server = new BoundedBuffer(); // now create the producer and consumer threads Producer producerThread = new Producer(server); Consumer consumerThread = new Consumer(server); producerThread.start(); consumerThread.start(); } 운영체제

41 프로세스간 통신(Inter-Process Communication)
통신 방식  한 시스템에서 둘 다 사용해도 됨 공유 메모리 방식(shared-memory) 응용 프로그램 작성자가 응용 레벨에서 통신기능 제공 (예)유한버퍼 생산자-소비자 문제 version 1 메시지 전달 방식(message-passing) IPC(interprocess-communication)기능 이용 : OS가 통신기능 제공 (예)유한 버퍼 생산자-소비자 문제 version 2 IPC 기본 구조(Basic Structure) IPC기능의 2연산 send (message) receive(message) 프로세스 P와 Q가 통신함  통신선이 전재 링크 공유 메모리 bus network send/receive 연산 운영체제

42 프로세스간 통신(Inter-Process Communication)
메시지 시스템을 구현하는 기법들 직접(direct) 또는 간접 통신 대칭(symmetric) 또는 비대칭(symmetric) 통신 자동(automatic) 또는 명시적(explicit) 버퍼링 복사(copy)에 의한 전송 또는 참고(reference)에 의한 전송 고정길이(fixed-sized) 또는 가변길이(variable-sized) 메시지 운영체제

43 프로세스간 통신(Inter-Process Communication)
명칭 부착(Naming) 1) 직접통신(Direct Communication) 대칭적 통신 : 두 프로세스(sender/receiver)가 상대의 이름을 호출 Send(P, message) : 프로세스 P에게 메시지 보냄 Receive(Q, message) : 프로세스 Q로부터 메시지 받음 비대칭적 통신 : sender만 receiver 호출 Receive(id, message) : 임의의 프로세스로부터 메시지 받음 id = 통신이 일어난 순간 메시지를 보낸 프로세스의 이름으로 설정됨 직접통신의 단점 프로세스 이름 바뀌면 전부 고쳐야(limited modularity) 2) 간접통신(Indirect Communication) mailbox(ports) 통해 통신 send(A, message) : mailbox A에 메시지 보냄 receive(A, message) : mailbox로부터 메시지 받음 mailbox의 구현 프로세스가 mailbox소유 OS가 mailbox소유 운영체제

44 프로세스간 통신(Inter-Process Communication)
동기화(Synchronization) Blocking send: 수신 프로세스가 메시지를 받을 때까지 멈춤 Nonblocking send: 메시지 보내고 다른 연산 계속 Blocking receive: 메시지가 있을 때까지 멈춤 Nonblocking receive: 올바른 메시지이거나 널 메시지이거나 상관하지 않고 받음 버퍼링(Buffering) 링크의 메시지 보유 용량 Zero capacity : rendez-vous(no buffering)…동기적 통신 Bounded capacity : 유한 길이 큐 이용…자동 버퍼링 Unbounded capacity : 무한 길이 큐 이용…자동 버퍼링 운영체제

45 프로세스간 통신(Inter-Process Communication)
자동 버퍼링 경우 보통 비동기적 통신(asynchronous communication)이 일어남 보낸 메시지 도착 여부 모름 꼭 알아야 할 경우 : 명시적 통신 P : send(Q, message); Q : receive(P, message); send(P, “acknowledgment”); receive(Q, message); 특별한 경우 비동기적 통신: 메시지 보낸 프로세스는 절대로 지연되지 않음 보낸 메시지 미처 받기 전에 새 메시지 보내면 이전 메시지 유실될 수 있음 메시지 유실 방지 위해 복잡한 명시적 동기화 필요 동기적 통신: 메시지 보낸 프로세스는 받았다는 회신 받을 때까지 기다림 Thoth OS : reply(P, message) 가 메시지 보낸 프로세스와 받는 프로세스의 수행 재개 Sun RPC(Remote Procedure Call) 동기적 통신(synchronous communication) sender : subroutine call  reply올 때까지 블록 됨 receiver : 계산 결과를 reply ( Information 참조) 운영체제

46 프로세스간 통신(Inter-Process Communication)
예외 조건(Exception Conditions) centralized 또는 distributed system에서 고장 발생시 오류의 회복(예외 조건) 필요 프로세스 종료(Process Terminates) P는 종료된 Q를 기다림  P는 블록 됨 P 종료 Q 종료 사실을 P에 알림 P가 종료된 Q에 메시지 보냄  Q의 reply 기다려야 할 경우 블록 됨 메시지 유실(Lost Messages) OS가 탐지 및 처리 책임 sender가 탐지 및 처리 책임 OS가 탐지, sender가 처리 훼손된 메시지(Scrambled Messages) 통신 채널의 잡음(noise) 때문  보통 OS가 재전송 오류검사코드(check sums, parity, CRC)으로 조사 운영체제

47 Mailbox를 이용하는 생산자-소비자 문제
import java.util.*; public class MessageQueue { public MessageQueue() { queue = new Vector(); } // This implements a nonblocking send public void send(Object item) { queue.addElement(item); // This implements a nonblocking receive public Object receive() { Object item; if (queue.size() == 0) return null; else { item = queue.firstElement(); queue.removeElementAt(0); return item; private Vector queue; 운영체제

48 메시지 시스템의 생산자 프로세스와 소비자 프로세스
MessageQueue mailBox; while (true) { Date message = new Date(); mailBox.send(message); } 소비자 프로세스 Date message =(Date) mailBox.receive(); if (message !=null) // consume the message 운영체제

49 메시지 시스템의 Producer.java import java.util.*;
class Producer extends Thread { public Producer(MessageQueue m) mbox = m; } public void run() Date message; while (true) int sleeptime = (int) (Server.NAP_TIME * Math.random() ); System.out.println("Producer sleeping for " + sleeptime + " seconds"); try { sleep(sleeptime*1000); } catch(InterruptedException e) {} message = new Date(); System.out.println("Producer produced " + message); // produce an item & enter it into the buffer mbox.send(message); private MessageQueue mbox; 운영체제

50 메시지 시스템의 Consumer.java import java.util.*;
class Consumer extends Thread { public Consumer(MessageQueue m) mbox = m; } public void run() Date message; while (true) int sleeptime = (int) (Server.NAP_TIME * Math.random() ); System.out.println("Consumer sleeping for " + sleeptime + " seconds"); try { sleep(sleeptime*1000); } catch(InterruptedException e) {} // consume an item from the buffer System.out.println("Consumer wants to consume."); message = (Date)mbox.receive(); if (message != null) System.out.println("Consumer consumed " + message); private MessageQueue mbox; 운영체제

51 메시지 시스템의 Server.java import java.util.*; public class Server {
public Server() // first create the message buffer MessageQueue mailBox = new MessageQueue(); // now create the producer and consumer threads Producer producerThread = new Producer(mailBox); Consumer consumerThread = new Consumer(mailBox); producerThread.start(); consumerThread.start(); } public static void main(String args[]) Server server = new Server(); public static final int NAP_TIME = 5; 운영체제

52 IPC 실례: POSIX Shared Memory
POSIX Shared Memory APIs 프로세스는 일차적으로 shmget (SHared Memory GET)을 이용하여 공유 메모리 세스먼트 생성 segment id = shmget(IPC PRIVATE, size, S_IRUSR | S_IWUSR); 프로세스는 공유 메모리에 접근하기 위해 shmat (SHared Memory ATtach)를 이용하여 자신의 주소 공간(address space)에 부착 shared memory = (char *) shmat(segment_id, NULL, 0); 프로세스는 반환된 포인터가 가리키는 공유 메모리에 read & write sprintf(shared memory, "Writing to shared memory"); 작업이 끝나면 프로세스는 shmdt (SHared Memory DeTach)를 이용하여 자신의 주소공간에서 공유 메모리를 분리 shmdt(shared memory); 마지막으로 프로세스는 shmctl(SHared Memory ConTroL operation)에 IPC_RMID 플래그를 지정하여 공유메모리 세그먼트를 시스템에서 제거 shmctl(segment_id, IPC_RMID, NULL); 운영체제

53 /oshome/final-src/chap3/shm-posix.c
#include <stdio.h> #include <sys/shm.h> #include <sys/stat.h> int main() { /* the identifier for the shared memory segment */ int segment_id; /* a pointer to the shared memory segment */ char* shared_memory; /* the size (in bytes) of the shared memory segment */ const int segment_size = 4096; /** allocate a shared memory segment */ segment_id = shmget(IPC_PRIVATE, segment_size, S_IRUSR | S_IWUSR); /** attach the shared memory segment */ shared_memory = (char *) shmat(segment_id, NULL, 0); printf("shared memory segment %d attached at address %p\n", segment_id, shared_memory); /** write a message to the shared memory segment */ sprintf(shared_memory, "Hi there!"); /** now print out the string from shared memory */ printf("*%s*\n", shared_memory); /** now detach the shared memory segment */ if ( shmdt(shared_memory) == -1) { fprintf(stderr, "Unable to detach\n"); } /** now remove the shared memory segment */ shmctl(segment_id, IPC_RMID, NULL); return 0; 운영체제

54 IPC 실례: Mach 분산시스템을 위한 OS 시스템 호출, task 간 정보전달을 메시지로 port(= mailbox)
task 생성  (kernel mailbox, notify mailbox) 생성 system calls msg_send msg_receive msg_rpc (remote procedure call) port_allocate : 새 mailbox 생성, buffer size = 8, FIFO order port_status : 주어진 mailbox의 메시지 수 반환 메시지 형태 고정길이 header 메시지 길이 두 mailbox 이름(그 중 하나는 sender의 mailbox; reply 위한 return address 포함) 가변길이 data portion: 정형화된(typed) 데이터 항목들의 리스트 운영체제

55 Mach send & receive send 연산 수신 mailbox가 full이 아니면 메시지 복사
기다리지 않고 즉시 복귀 메시지를 임시로 cache : 메시지 하나만 OS가 보관 (메시지가 실제로 목표 mailbox에 들어갔을 때 reply ; only one pending message) line printer driver 등 서버 태스크 경우 receive 연산 어떤 mailbox 또는 mailbox set로부터 메시지를 읽을지를 명시 지정된 mailbox로부터 또는 mailbox set 중 한 mailbox로부터 메시지 수신 읽을 메시지 없으면 최대 n 밀리초 대기하거나 대기하지 않음 메시지 시스템의 단점 double copy(sender  mailbox, mailbox  receiver) Mach는 virtural memory 기법으로 두 번 복사 않음(송신 스레드와 수신 스레드를 같은 주소 공간으로 mapping 시킴) 운영체제

56 IPC 실례: Windows XP XP subsystem server와 메시지 전달 방식으로 통신 : 지역 프로시주어 호출 기능(LPC; Local Procedure Call facility) LPC: RPC(Remote Procedure Call) 기법과 유사 연결 포트(connection port)와 통신 포트(communication port) 사용 통신 작업 클라이언트가 연결 포트 객체에 대한 handle을 open 클라이언트가 연결 요청 서버는 두 개의 사적인(private) 통신 포트를 생성하고 클라이언트에게 두 포트 중 하나의 handle을 돌려줌 클라이언트와 서버는 해당 통신 포트의 handle을 이용하여 메시지를 보내거나, 응답호출(callback)을 하거나, 응답(reply)을 기다림 세 가지 메시지 전달 기법 포트의 메시지 큐(~256 bytes)를 중간 저장소로 이용, 즉시 응답하기 어려울 때 알려주는 callback 기법 사용 가능 전송할 메시지가 크면 공유 메모리인 섹션 객체(section object)를 이용, 섹션 객체의 포인터와 크기 정보 전송하여 데이터 복사 피함, 즉시 응답하기 어려울 때 알려주는 callback 기법 사용 가능 quick LPC : 클라이언트가 연결 요청 후 quick LPC 지시, 서버는 클라이언트 전용 서버 스레드(dedicated server thread) 생성 연결 요청, 메시지 담을 64KB 섹션 객체, 동기화를 수행하는 한 쌍의 사건 객체(event pare object) 처리 장점 : 메시지 복사, 포트 객체 사용, 호출한 클라이언트 파악위한 overhead 제거 단점 : 다른 두 방법보다 많은 자원 사용 메시지 전달 overhead 감소 위해 여러 메시지들을 한 메시지로 batch 하기도 함 운영체제

57 Windows XP 지역 프로시저 호출 운영체제

58 클라이언트-서버 통신(1): 소켓 (Socket)
소켓은 종단점(endpoint) 프로세스간 상호 양방향 통신 방식 종단점 = IP 주소와 포트 번호 결합 소켓 :6666 호스트 포트 6666 통신은 한 쌍의 소켓을 포함 네트워크를 통한 통신 가능 소켓을 통한 프로세스 통신은 클라이언트-서버 모델(client-server model) 활용 한 기계에 존재하는 파일을 다른 기계에서 프린트 한 기계에서 다른 기계로 파일을 전송

59 Socket 운영체제

60 Time-of-Day: Server.java
import java.net.*; import java.io.*; public class DateServer { public static void main(String[] args) { try { ServerSocket sock = new ServerSocket(6013); // now listen for connections while (true) { Socket client = sock.accept(); // we have a connection PrintWriter pout = new PrintWriter(client.getOutputStream(), true); // write the Date to the socket pout.println(new java.util.Date().toString()); // close the socket and resume listening for more connections client.close(); } catch (IOException ioe) { System.err.println(ioe); (Linux) $ Java Server 실행은 방화벽 꺼야 함 # /sbin/service iptables stop 또는 # /etc/init.d/iptables stop

61 Time-of-Day: Client.java
import java.net.*; import java.io.*; public class DateClient { public static void main(String[] args) { try { // this could be changed to an IP name or address other than the localhost Socket sock = new Socket(" ",6013); InputStream in = sock.getInputStream(); BufferedReader bin = new BufferedReader(new InputStreamReader(in)); String line; while( (line = bin.readLine()) != null) System.out.println(line); sock.close(); } catch (IOException ioe) { System.err.println(ioe);

62 클라이언트-서버 통신(2): 원격 프로시저 호출 RPC
한 호스트의 클라이언트 프로시주어가 원격에 있는 서버 호스트의 프로시저를 호출할 수 있게 하는 가장 일반적인 클라이언트/서버 지원 기법 구조화가 잘된 고수준 (high-level) 메시지 전송 (cf.) 소켓 통신은 저수준 패킷 스트림 전송 Sun의 NFS (Network File System) 구현에 유용하게 이용됨 rpcbind (전신은 portmapper)가 port number 111로 서비스 (ref.) /etc/services 의 sunrpc Sun RPC가 가장 많이 이용됨 역사 1981 RPC 기반 Xerox Courier 1985 Sun RPC package: ONC(Open Network Computing) RPC, XDR(eXternal Data Representation) TCP 또는 UDP 상에서 동작하는 socket API들로 구현 공개 소스 RPCSRC 1990 초 TLI (Transport Layer Interface): XTI(X/Open Transport Interface)의 전신  공개 소스 TI (Transport Independent)-RPC 1980 중반: RPC 기반 Apollo NCA(Network Computing Architecture) RPC, NIDL(Network Interface Definition Language) 1989 DCE(Distributed Computing Environment) RPC

63 Execution of RPC (Remote Procedure Call)
네트워크 상의 프로세스들 사이에서 프로시저 호출(procedure calls)을 추상화 클라이언트 측 스터브(stub) 원격 서버와 포트를 찾고 파라미터를 정돈(marshal)하여 메시지 전달 서버 측 스터브(stub) 원격 서버의 프로시저에 대한 대행자(proxy)로서 메시지 받아 정돈된 파라미터를 풀어(unmarshal) 프로시저를 수행함 운영체제

64 Sun RPC 예제 1: DATE_PROG 구성 소스 코드
rpcgen: remote procedure interface(date.x)를 컴파일하여 server stub와 client stub를 생성 XDR(eXternal Data Representation): 다른 시스템 간에 이식 가능한 형태로 데이터를 코드화하는 표준 방법 run-time library: 모든 세세한 것들을 다룸; –lnsl(Network Service Library) 소스 코드 RPC 명세 파일 date.x 서버 프로그램 date_proc.c 클라이언트 프로그램 rdate.c

65 Sun RPC 예제 1: DATE_PROG 처리 방법 % rpcgen date.x
% gcc -o date_svc date_proc.c date_svc.c –lnsl % gcc -o rdate rdate.c date_clnt.c –ln니 실행 방법 서버 호스트에서 $ date_svc & ( Linux에서는 super user 만 서버 실행 가능) 클라이언트 호스트에서 $ ./rdate 호스트이름(도메인이름 또는 IP 주소) (실행 파일이 rdate인 경우 /usr/bin/rdate가 이미 존재할 수 있으므로 rdate 명령 앞에 현재 디렉토리 ./ 붙여서 ./rdate로 실행시킴) time on host = 00:00:00 GMT(Greenwitch Mean Time) January 1, 1970부터의 초의 수 time on host = Tue Mar 13 14:06: 실습 (반대의 경우도 실습) 서버( ) 호스트: $ date_svc & 클라이언트( ) 호스트: $ ./rdate (cf.) $ which rdate  /usr/bin/rdate

66 Sun RPC 예제 1: DATE_PROG

67 Sun RPC 예제 1: DATE_PROG RPC 명세 파일 : date.x program DATE_PROG {
version DATE_VERS { long BIN_DATE(void) = 1 ; /* procedure no. = 1 */ string STR_DATE(long) = 2 ; /* procedure no. = 2 */ } = 1 ; /* version no. = 1 */ } = 0x ; /* program no. = 0x */ 프로그램 번호 0x ~ 0x1fffffff Sun에 의해 정의된 0x ~ 0x3fffffff 사용자에 의해 정의된 0x ~ 0x5fffffff 일시적인 (transient) 0x ~ 0xffffffff 예약된 (reserved)

68 Sun RPC 예제 1: DATE_PROG 서버 프로그램 : date_proc.c (Unix version)
#include <rpc/rpc.h> #include "date.h" long * bin_date_1() { static long timeval ; long time() ; timeval = time((long *) 0) ; return(&timeval) ; } char ** str_date_1(bintime) long *bintime ; static char *ptr ; char *ctime() ; ptr = ctime(bintime) ; return(&ptr) ;

69 Sun RPC 예제 1: DATE_PROG 클라이언트 프로그램 : rdate.c (Unix version)
#include <stdio.h> #include <rpc/rpc.h> #include "date.h" /* generated by rpcgen */ main(argc, argv) int argc; char *argv[]; { CLIENT *cl; /* RPC handle */ char *server; long *lresult; /* return value from bin_date_1() */ char **sresult; /* return value from str_date_1() */ if (argc != 2) fprintf(stderr, "usage: %s hostname\n", argv[0]); server = argv[1]; if ((cl = clnt_create(server,DATE_PROG,DATE_VERS,"udp")) /* client handle 생성 */ == NULL) clnt_pcreateerror(server); if ((lresult = bin_date_1(NULL, cl)) == NULL) clnt_perror(cl, server); printf("time on host %s = %ld\n", server, *lresult); if ((sresult = str_date_1(lresult, cl)) == NULL) printf("time on host %s = %s", server, *sresult); clnt_destroy(cl); }

70 Sun RPC 예제 1: DATE_PROG 서버 프로그램 : date_proc.c (Linux version)
#include <stdio.h> #include <rpc/rpc.h> #include "date.h" #include <time.h> long *bin_date_1_svc(void *arg1, struct svc_req *arg2) { static long timeval; /* must be static */ timeval = time((long *) 0); return(&timeval); } char **str_date_1_svc(long *bintime, struct svc_req *arg2) static char *ptr; /* must be static */ ptr = ctime(bintime); /* convert to local time */ return(&ptr);

71 Sun RPC 예제 2: SQUARE_PROG
RPC 명세 파일 : square.x struct square_in { /* input argument */ long arg1; }; struct square_out { /* output result */ long res1; program SQUARE_PROG { version SQUAREPROG { square_out SQUARE_PROC (square_in) = 1; /* procedure no. =1 */ } = 1; /* version number */ } = 0x /* program number */ 소스 코드 : square.x server.c client.c 처리 방법 % rpcgen square.x % gcc -o server server.c square_svc.c square_xdr.c -lnsl % gcc -o client client.c square_clnt.c square_xdr.c –lnsl (RPC 명세 파일에 구조체를 포함하기 때문에 square_xdr.c 파일이 생성되므로 컴파일시 square.xdr.c 파일을 반드시 포함해야 함)

72 Sun RPC 예제 2: SQUARE_PROG

73 Sun RPC 예제 2: SQUARE_PROG

74 Sun RPC 예제 2: SQUARE_PROG
서버 프로그램 : server.c (Unix version) #include “square.h” square_out * squareproc_1 (square_in *inp, struct svc_req *rqstp) { static square_out out ; out.res1 = inp -> arg1 * inp -> arg1 ; return (&out); }

75 Sun RPC 예제 2: SQUARE_PROG
클라이언트 프로그램 : client.c (Unix version) #include “square.h” int main(int argc, char **argv) { CLIENT *cl ; square_in in ; square_out *outp ; if ( argc != 3 ) clnt_perror(cl, “usage : client <hostname> <interger_value>”); cl = cInt_create(argv[1], SQUARE_PROG, SQUARE_VERS, “tcp”); in.arg1 = (long)atol(argv[2]); if ( ( outp = squareproc_1(&in, cl) ) == NULL) clnt_perror( cl, argv[1] ) ; printf(“result : %ld\n”, outp -> res1); exit(0) }

76 Sun RPC 예제 2: SQUARE_PROG
서버 프로그램 : server.c (Linux version) #include "square.h" square_out * squareproc_1_svc(square_in *inp, struct svc_req *rqstp) { static square_out out; out.res1 = inp->arg1 * inp->arg1; return(&out); }

77 클라이언트-서버 통신(3): 원격 메소드 호출 RMI
RPC의 Java 버전 저수준(low-level) 소켓을 이용하지 않고 원격 객체의 메소드를 호출할 수 있는 방법을 제공하는 객체 지향 언어인 Java 기반의 분산 컴퓨팅 환경(클라이언트/서버 지원)을 위한 미들웨어(RPC와 유사) 스레드(thread)가 원격 객체(Remote Object)의 메소드(method) 호출 다른 Java Virtual Machine 상에 있는 객체는 “원격” 객체 RPC 보다 좋은점 객체 지향적이다. 프로그램 작성 및 사용이 쉽다. 안전하고 보안성이 있다. 기존 시스템과 통합해서 사용할 수 있다. 작성 절차 원격 인터페이스를 정의한다. 원격 인터페이스를 구현(implement)하는 원격 객체(서버)를 작성한다 원격 객체를 이용하는 프로그램(클라이언트)을 작성한다. stub와 skeleton 클래스를 생성한다. rmiregistry를 실행시킨다. 서버와 클라이언트를 실행시킨다.

78 RMI (Remote Method Invocation)
RPC versus RMI RPC : Procedural Programming Style RMI : Object-Oriented Programming Style RPC의 매개변수 : Ordinary Data Structures RMI의 매개변수 : Objects Stubs and Skeletons “Stub” 클라이언트에 상주하는 원격 객체의 대리인(proxy) 매개변수들을 “Marshalls”(메소드 이름과 인자들의 꾸러미 생성)해서 서버로 보냄 “Skeleton” 서버에 상주 매개변수를 “Unmarshalls” 해서 서버에 전달함 매개변수 Marshall된 매개변수가 Local (Non-Remote) Objects이면 객체를 바이트 스트림으로 기록해 주는 객체 순서화(Object Serialization) 기법을 이용해서 복사에 의해(by Value) 전달 Marshall 된 매개변수가 Remote Objects이면 참조에 의해(by Reference) 전달 : RMI의 장점 Remote objects java.rmi.Remote를 확장한 Interface로 선언되어야 함 … extends java.rmi.Remote 모든 메소드는 java.rmi.RemoteException을 발생시켜야 함 … throws java.rmi.RemoteException

79 RMI (Remote Method Invocation)
RMI(Remote Method Invocation)는 RPC와 유사한 Java 기능 RMI는 한 컴퓨터의 Java 프로그램이 다른 컴퓨터의 원격 객체 메소드를 호출할 수 있게 함 운영체제

80 매개변수 정돈 (Marshalling Parameters)
운영체제

81 RMI 프로그램 예제 server client 원격 인터페이스 구현 MessageQueueImpl.java
javac MessageQueueImpl.class MessageQueue.java MessageQueueImpl_skel.class rmic MessageQueueImpl_stub.class Factory.java Producer.java javac Factory.class Consumer.java client

82 RMI 프로그램 예제 구성 원격 인터페이스: MessageQueue.java
서버 프로그램: MessageQueueImpl.java 클라이언트 프로그램: Factory.java, Producer.java, Consumer.java 원격 서버와 클라이언트 Naming 시 반드시 ip와 고유한 service 이름 명시 (서버) Naming.rebind("// /myMessageServer", server); (클라이언트) Naming.lookup("rmi:// /myMessageServer", server); Policy File : New with Java 2 grant { permission java.net.SocketPermission "*: ", "connect,accept"; }; (Linux) $ Java Server 실행은 방화벽 꺼야 함 # /sbin/service iptables stop 또는 # /etc/init.d/iptables stop

83 RMI 프로그램 예제 실행 순서 모든 소스 파일 컴파일
$ javac MessageQueue.java MessageQueueImpl.java Factory.java Producer.java Consumer.java rmic로 stub와 skeleton class 파일 생성 $ rmic MessageQueueImpl 레지스트리 서비스 시작 (rmiregistry) … osagent 또는 rpcbind 디몬에 해당 $ rmiregistry & (Unix & Linux) 또는 C:\> start rmiregistry (Windows) 원격 서버 객체의 인스턴스 생성 (JDK 1.2 이상 버전에서는 인증해 주어야 함) $ java -Djava.security.policy=java.policy MessageQueueImpl (JDK 1.2 이상) 또는 $ java MessgeQueueImpl (JDK 1.1) 클라이언트에서 원격 객체 실행 시작 $ java -Djava.security.policy=java.policy Factory (JDK .2 이상) 또는 $ java Factory (JDK 1.1)

84 3장 정리 PCB & task_struct 프로세스 생성과 종료 fork fork + exec
유한 버퍼 생산자-소비자(bounded-buffer producer-consumer) 문제 Version 1: 공유 메모리를 이용한 해결책 (3.4.1절) Version 2: 메시지 전달(IPC)을 이용한 해결책 (3.4.2절) 클라이언트-서버 통신 Socket RPC RMI 운영체제


Download ppt "제2부 프로세스 관리 (Process Management)"

Similar presentations


Ads by Google