Module 4: Processes

Similar documents
6주차.key

4장

Microsoft PowerPoint os4.ppt

Microsoft PowerPoint - o3.pptx

10주차.key

3ÆÄÆ®-11

untitled

chap 5: Trees

Microsoft PowerPoint os3.ppt [호환 모드]

강의10

Chap06(Interprocess Communication).PDF

Microsoft PowerPoint - 04-UDP Programming.ppt

UniStore

02 C h a p t e r Java

<C0CCBCBCBFB52DC1A4B4EBBFF82DBCAEBBE7B3EDB9AE2D D382E687770>

Figure 5.01

10.

Chap7.PDF

ABC 11장

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

Microsoft PowerPoint - o8.pptx

13주-14주proc.PDF

rmi_박준용_final.PDF

11장 포인터

슬라이드 1

Microsoft PowerPoint - Lecture_Note_7.ppt [Compatibility Mode]

example code are examined in this stage The low pressure pressurizer reactor trip module of the Plant Protection System was programmed as subject for

Chapter 4. LISTS

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

PCServerMgmt7

Microsoft PowerPoint - RMI.ppt

Chapter #01 Subject

1

Chap04(Signals and Sessions).PDF

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

SRC PLUS 제어기 MANUAL

PowerPoint 프레젠테이션

제11장 프로세스와 쓰레드

untitled


PowerPoint 프레젠테이션

좀비프로세스 2

The Self-Managing Database : Automatic Health Monitoring and Alerting

(Asynchronous Mode) ( 1, 5~8, 1~2) & (Parity) 1 ; * S erial Port (BIOS INT 14H) - 1 -

/chroot/lib/ /chroot/etc/

PowerPoint 프레젠테이션

슬라이드 1

목차 BUG offline replicator 에서유효하지않은로그를읽을경우비정상종료할수있다... 3 BUG 각 partition 이서로다른 tablespace 를가지고, column type 이 CLOB 이며, 해당 table 을 truncate

BMP 파일 처리

Microsoft Word - FunctionCall

제9장 프로세스 제어

chapter4

hlogin2

김기남_ATDC2016_160620_[키노트].key

자바-11장N'1-502

Deok9_Exploit Technique

03장.스택.key

Microsoft PowerPoint - chap9 [호환 모드]

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

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

K&R2 Reference Manual 번역본

PowerPoint 프레젠테이션

Microsoft PowerPoint - Supplement-03-TCP Programming.ppt [호환 모드]

Microsoft PowerPoint - 03-TCP Programming.ppt

휠세미나3 ver0.4

untitled

chap7.key

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

PowerPoint 프레젠테이션

<4D F736F F F696E74202D20BBB7BBB7C7D15F FBEDFB0A3B1B3C0B05FC1A638C0CFC2F72E BC8A3C8AF20B8F0B5E55D>

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

2009년 상반기 사업계획

SMB_ICMP_UDP(huichang).PDF

02장.배열과 클래스

untitled

Microsoft PowerPoint oshw1.ppt [호환 모드]

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션



Chapter 4. LISTS

Chap 6: Graphs

슬라이드 1

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

Something that can be seen, touched or otherwise sensed

thesis

MAX+plus II Getting Started - 무작정따라하기

No Slide Title

2009년 상반기 사업계획

Analytics > Log & Crash Search > Unity ios SDK [Deprecated] Log & Crash Unity ios SDK. TOAST SDK. Log & Crash Unity SDK Log & Crash Search. Log & Cras


Microsoft PowerPoint - ch07 - 포인터 pm0415

NoSQL

Microsoft Word - Network Programming_NewVersion_01_.docx

10X56_NWG_KOR.indd

운영체제란? PC를구입하면 Windows XP, Windows 7, Linux, MS-DOS Mac OSX, ios 운영체제 : Operating System 운영체제가없는컴퓨터? 컴퓨터 : 프로세서와메모리 전원을켜면어떤일이? 휘발성메모리 - 야생마 프로그램을실행하려면

제1장 Unix란 무엇인가?

MySQL-Ch10

Mobile Service > IAP > Android SDK [ ] IAP SDK TOAST SDK. IAP SDK. Android Studio IDE Android SDK Version (API Level 10). Name Reference V

Microsoft PowerPoint APUE(Intro).ppt

Transcription:

Chapter 3 : Processes Yoon-Joong Kim Hanbat National University, Computer Engineering Department

Chapter 3: Processes 3.1 Process Concept 3.2 Process Scheduling 3.3 Operations on Process 3.4 Interprocess Communication 3.5 Examples of IPC Systems 3.6 Communication in Client-Server Systems

Chapter 3: Processes 3.1 Process Concept Process state, PCB 3.2 Process Scheduling Long-term/Short-term/Medium-Term Scheduler, Context Switch, 3.3 Operations on Process Process Creation : POSIX: fork+exit, WIN32: CreatProcess, C#: Process.Start Process Termination : exit, abort C#: nprocess.kill 3.4 Interprocess Communication Shared Memory Model, Message Passing Model Bounded-Buffer Producer-Consumer Problem Message Passing Model : Direct Communication Send(P,Message)- Receive(Q,Message) Send(P,Message)-Receive(pID,Message)

Chapter 3: Processes 3.4 Interprocess Communication Shared Memory Model, Message Passing Model Bounded-Buffer Producer-Consumer Problem Message Passing Model by Naming Processes Direct Communication : One link between processes Send(P,Message)- Receive(Q,Message) : symmetric Send(P,Message)-Receive(pID,Message) : asymmetric Indirect Communication : Shared mail-box by processes Send(A,Message)-Receive(A,Message) Message Passing Model by Buffering Zero / Bounded / Unbounded Capacity Communication 고정크기 - 가변크기 Message Passing Model by Buffering by Synchronization Blocking-Synchronous / Nonblocking-asynchronous Communication

Chapter 3: Processes 3.5 Examples of IPC Systems POSIX : Memory Shred API Mach : Memory Passing Windows XP : LPC 3.6 Communication in Client-Server Systems Client-Server System Sockets, RPC, RMI(JAVA) Socket Program example(c#)

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

3.1 Process Concept(cont.) Fig. 3.1 Process in Memory

3.1 Process Concept(cont.) 프로세스상태 (Process State) 생성 (new) 수행 (running) : CPU 가실행, 명령어실행대기 (waiting) : I/O 완료나 signal 기다림, 이벤트발생대기준비 (ready) : Processor 를받을준비가됨종료 (terminated) Fig. 3.2 Diagram of Process State

3.1 Process Concept(cont.) 프로세스제어블럭 (Process Control Block, PCB) PCB 는각프로세스의상태및관리를위한정보가표현되는자료구조이다. PCB Solaris 10 Unix: /usr/include/sys/proc.h (99 행 ) Fedora Linux: /usr/src/kernels/linux-2.6.35.6/include/linux/sched.h (1167 행 ) 프로세스상태 : 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

3.1 Process Concept(cont.) PCB 와프로세스 프로세스의생성시 : OS 가프로세스를위하여 PCB 의메모리를할당한다. OS 가 PCB 를초기화한다. OS 가해당큐에 PCB 를배치한다. 프로세스가활성화상태에서 OS 는 PCB 를해당큐로이동시킨다. 프로세스의종료시 OS 가 PCB 를해제한다 Fig. 3.3 Process Control Block (PCB)

3.2 Process Scheduling Process scheduling : 다중프로그램의수행을위하여일정절차에따라프로세스한개를선택하고 CPU 를할당하여실행을제어하는절차 Long-term scheduler (or job scheduler) Pool => memory(degree of multiprogramming) Unix 같은시분할시스템에는없음 Short-term scheduler (or CPU scheduler) CPU 할당 : must be very fast medium-term scheduler(swapper) degree of multiprogramming 을줄임 memory backing store Fig 3.7 Queueing-diagram representation of process scheduling Fig. 3.8 Addition of Medium Term Scheduling to queueing diagram

3.2 Process Scheduling(cont.) 스케줄링큐 (Scheduling Queues) 작업큐 (job queue) : memory 할당기다리는큐 (disk 에서 ) 준비큐 (ready queue) : CPU 에할당기다리는큐 장치큐 (device queue() : 입출력기다리는큐 큐잉도표 (queueing diagram) : 그림 3.7 Fig 3.7 The ready queue and various I/O device queues

3.2 Process Scheduling(cont.) I/O and CPU bound 프로세스 I/O-bound process spends more time doing I/O than computations, many short CPU bursts CPU-bound process spends more time doing computations; few very long CPU bursts Long-term scheduler should select a good process-mix of I/O-bound and CPU-bound process.

3.2 Process Scheduling(cont.) 문맥전환 (Context Switch) CPU 가한프로세스에서다른프로세스로 switch 될때 프로세스의실행 (cpu) 을정지할때 현프로세스의상태 (context) 를 PCB 에저장 새프로세스의실행시작시 새프로세스의상태 (context) 를 PCB 로부터복원 context-switch time : 1-1000microsecond 프로세스의 Context 는 PCB 에표현된다.

3.3 Operations on Process 3.3.1 Process Creation 부모프로세스가자식프로세스를생성한다. 트리를형성한다. 프로세스생성시스템호출 : fork/vfork, exec, CreateProcess, Process.Start 부모프로세스 자식프로세스 : 부모의데이터영역복제, cf. vfork 자원공유방법 ( 메모리파일등 ) 자식프로세스가부모프로세스의자원을전부공유, 일부공유또는공유하지못할수도있다. 프로세스생성후 부모자식프로세스모두동시실행 부모프로세스는모든자식이끝날때까지기다림 : wait system call 로

3.3 Operations on Process(cont.) 전형적인 Unix System 의프로세스트리예

3.3 Operations on Process(cont.) A tree of process on typical Solaris system Fig. 3.9 A tree of process on typical Solaris system

3.3 Operations on Process(cont.) 자식프로세스의형태 ( 주소공간의관점에서 ) 부모의것을복제 : fork 자식은새로운프로그램을가짐 : fork+exec Unix의예 : fork + exec의예 fork : 자식프로세스생성, 모든프로세스는 PID를가짐 fork+exec : 자식생성후자식을위한새프로그램로드 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);

3.3 Operations on Process(cont.) Unix fork() 로프로세스생성하는 C 코드 int main() { pid_t pid; pid = fork(); /* create new process */ if (pid < 0) { /* error occurred */ fprintf(stderr, "Fork Failed"); exit(-1); else if (pid == 0) { /* child process */ execlp("/bin/ls", "ls", NULL); /* execute child process*/ else { /* parent process */ /* parent will wait for the child to complete */ wait (NULL); printf ("Child Complete"); exit(0); /* terminate successfully */ 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); Fig. 3.10 Creating a separate process using the UNIX fork() system call

3.3 Operations on Process(cont.) Unix fork() 로프로세스생성하는 C 코드 int main() { Int x=10000; pid_t pid; pid = fork(); /* create new process */ if (pid == 0) { /* child process */ x=x+10000; printf( child:%d\n,x); else { /* parent process */ sleep(5); x=x-10000; printf ( parent::%d\n,x); wait(null); 결과 child:20000 parent : 0 int main() { Int x=10000; pid_t pid; pid = vfork(); /* create new process */ if (pid == 0) { /* child process */ x=x+10000; printf( child:%d\n,x); else { /* parent process */ sleep(5); x=x-10000; printf ( parent::%d\n,x); wait(null); 결과 child:20000 parent :10000

3.3 Operations on Process(cont.) Fork 실행전후의구조 (linux 에서 ) child data pid x : 10000 parent data parent code pid x : 10000. if(pid==0) pid=fork(); x=10000; xs esp eip=100 eax= 0 pid=40 parent data parent/child code pid x : 10000. if(pid==0) pid=fork(); x=10000; 101 100 99 ss esp eip=100 eax=41 pid=40 ss esp eip=100 eax=0 0 pid=41 Kernel mode stack task_struct memory parent task_nion (pcb) Figure a. fork() 실행전 memory parent task_nion (pcb) Figure b. fork() 실행후 child task_nion (pcb) system call fork() 의처리 fork() : 명령어 int 0x80, 인터럽트처리루틴 (ISR1) 로점프하여다음을처리 cpu 의주요레지스터 (ss,esp,eflag,cs,eip 등 ) 들을프로세스의 kernel mode stack 으로저장 system call sys_fork() ISR2 를호출한다. sys_fork() : ISR2 호출 do_fork() do_fork() core 복제, 부모프레세스의 core image( 코드, 데이터, 스택 ) 복제 task_union(process descriptor,pcb) 복제 자신의 task_struct 에정보조정 : 복제된 core image 위치, pid 등 자시프로세스를프로세스큐ㅡ런큐에삽입 자식에게는 0 부모에게는 pid 를리턴 ( 자식의 KMS.eax=0, 부모 KMS.eax= 자식의 pid)

3.3 Operations on Process(cont.) Win32 API 를이용한새프로세스생성 (C ) #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) ); // Start the child process. if(!createprocess( NULL, // No module name (use command line). "C:\\WINDOWS\\system32\\mspaint.exe", // Command line. NULL, // Process handle not inheritable. NULL, // Thread handle not inheritable. FALSE, // Set handle inheritance to FALSE. 0, // No creation flags. NULL, // Use parent's environment block. NULL, // Use parent's starting directory. &si, // Pointer to STARTUPINFO structure. &pi ) // Pointer to PROCESS_INFORMATION structure. ) CloseHandle( pi.hthread );; handles.finite );etlasterror() );

Win32 API 를이용한새프로세스생성 (C# ) using System.Diagnostics; using System.Runtime.InteropServices; namespace ProcessBasic { class Program { static void Main(string[] args) { STARTUPINFO si = new STARTUPINFO(); PROCESS_INFORMATION pi = new PROCESS_INFORMATION(); CreateProcess("C:\\WINDOWS\\SYSTEM32\\Calc.exe", null, IntPtr.Zero, IntPtr.Zero, false, 0, IntPtr.Zero, null, ref si, out pi); // "C:\\WINDOWS\\SYSTEM32\\Calc.exe", // 생성될프로세스의이름 (path) // null, // 생성될프로세스에인자전달 ( 변수만가능 ) // IntPtr.Zero, // 프로세스보안속성지정 // IntPtr.Zero, // 쓰레드보안속성지정 // false, //TRUE: 부모쓰레드가소유하고있는상속가능한핸들을상속한다. // 0, / 생성되는프로세스의특성을결정짓는옵션 ( 우선순위 ) // IntPtr.Zero, // 생성하는프로세스의 Environment Block 지정 NULL: 부모환경복사 // null, // 생성하는프로세스의현재디렉토리성정 NULL: 부모의현재디렉토리 // ref si, // STARTUPINO 구조체변수를초기화한후변수포인터로전달 // out pi // 생성하는프로세스리정보를얻기위한인자 PROCESS_INFORMATION 구조체변수의주소값으로인자전달 Console.ReadLine();

Win32 API 를이용한새프로세스생성 (C# )

Result s : Process 객체를이용한방법 (C#)

3.3.2 Process Termination 프로세스종료 (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;

exit example: mystatus.c & myexit.c $ cat mystatus.c #include <stdio.h> main () { int pid, status, childpid; $ cat myexit.c #include <stdio.h> main () { printf ("I'm going to exit with return code 77\n"); exit (77); 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 ()); // execl ("/bin/ls", "ls", "-li", (char *)0); execl ("/export/home/mysung/osprog/myexit", "myexit", (char *)0); exit (42); /* Exit with a silly number */ printf ("PID %d terminates\n", getpid () );

Process.Kill() public void KillProcess() { Process myprocess = Process.GetCurrentProcess(); Console.WriteLine(" myprocess id/name:" + myprocess.id+"/"+myprocess.processname); //Create a process for 'NotePad.exe string Application = Environment.GetEnvironmentVariable("windir") + @"\Notepad.exe"; Process nprocess= Process.Start(Application); Console.WriteLine("The generated Process ID/Name:{0/{1", nprocess.id, nprocess.processname); nprocess = Process.Start(Application); Console.WriteLine("The generated Process ID/Name:{0/{1", nprocess.id,nprocess.processname); Process[] nprocesses = Process.GetProcessesByName("Notepad"); for(int i=0; i<nprocesses.length; i++) { Console.ReadKey(); Console.WriteLine("The Process ID/Name:{0/{1 has been killed", nprocesses[i].id,nprocesses[i].processname); nprocesses[i].kill(); Console.ReadKey(); Console.WriteLine("The main Process ID/Name:{0/{1 has been killed", myprocess.id,myprocess.processname); myprocess.kill();

3.4 Interprocess Communication 두종류의프로세스 독립적프로세스 (Independent Processes) 프로세스간영향을받을필요가없다. 프로세스협조 ( Coorperating Processes) 상호통신 (IPC, InterProcess Communication ) 이필요하다. 공유메모리, 메시지매핑 협조의필요성 예 IPC 의두모델 정보공유 (information sharing) 계산속도증가 (computation speedup) : parallel computing 으로 모듈화 (modularity) 편이성 (convenience) : parallel computing 으로 생산자소비자문제 공유메모리 (Shared Memory) 메세지전달 (Message Passing) CPU Memory P 1 Shared Memory P 2 OS Post office mailbox CPU Memory P 3 port OS

3.4 Interprocess Communication Fig. 3.13 Communication models (a)message Passing (b) Shared Memory

3.4.1 Shared-Memory Systems(cont.) 프로세스협조예 : 생산자-소비자 (producer-consumer) 문제 compiler : assembly code 생산 assembler : assembly code 소비, object code 생산 loader : object code 소비 생산자와소비자문제 buffer가필요 생산자와소비자의동기화필요 ( 생산되지않은자료소비하지않게 ) 버퍼의종류 ( 생산자-소비자문제종류 ) 1. 무한버퍼 (unbounded-buffer) 생산자-소비자문제 생산자는항상생산, 소비자는소비할자료를기다릴수도 2. 유한버퍼 (bounded-buffer) 생산자-소비자문제 Memory P 1 Shared Memory P 2 kerne l Compiler (producer) Assembly code Assembler (consumer) 버퍼가꽉차있으면생산자가대기, 버퍼가비어있으면소비자가대기 유한버퍼생산자-소비자문제 (bounded-buffer producer-consumer problem) 스레드 (LWP) 로처리하면효과적이다 방법1: 공유메모리를이용한방법 (3.4.1절) 방법 2: 메시지전달을이용한방법 (3.4.2절) 방법3: 세마포어를이용한방법 (6.6.1절) 방법4: 세마포어와스레드를이용한방법 (6장프로젝트 p266)

3.4.1 Shared-Memory Systems(cont.) synchronization synchronization Bounded-Buffer Shared-Memory Solution Producer item nextproduced; while (true) { /* Produce an item in nextproduced */ while ((( (in+1) % BUFFER_SIZE) == out) ; /* do nothing -- no free buffers */ buffer[in] = nextproduced; in = (in + 1) % BUFFER SIZE; int out = 0; //used by consumer Consumer item nextconsumed; while (true) { while (in == out) ; // do nothing -- nothing to consume nextconsumed = buffer[out]; // remove an item from the buffer out = (out + 1) % BUFFER SIZE; /* consume the item in nextconsume */ Solution is correct, but can only use BUFFER_SIZE-1 elements Shared data #define BUFFER_SIZE 10 typedef struct {... item; item buffer[buffer_size]; int in = 0; //used by producer

IPC - 3.4.2 message Passing Systems Memory Memory Q No shared memory between 2 processes P Just wires (bus or network) kernel h/w kernel h/w Ask OS to send message IPC system call Send(host, process, message) Direct Do you know his PID (at coding time)? What if that his PID changes after coding? Send(host, port #) - Indirect Let Post-office(OS) provide mailbox code program using mailbox # (port)

프로세스간통신방식 3.4.2 message Passing Systems 메시지전달방식 (message-passing) IPC(interprocess-communication) 기능이용 : OS 가통신기능제공 ( 예 ) 유한버퍼생산자 - 소비자문제방법 2 공유메모리방식 (shared-memory) 응용프로그램작성자가응용레벨에서통신기능제공 ( 예 ) 유한버퍼생산자 - 소비자문제방법 1 IPC 기본구조 (Basic Structure) IPC 을위한 2 연산 send (message) receive(message) 프로세스 P 와 Q 가통신함 통신선 (uni or bi directional) 연결된상태에서 : 공유메모리, 네트워크, 하드웨어버스 send/receive 로연산 ( 통신 ) 링크의논리적구현과송수신연산의구현에따른분류 직접 (direct) 또는간접통신 : 하나의링크 / 우편함이용 동기식또는비동기식통신 : 대칭 (symmetric) 또는비대칭 (symmetric) 통신 : 연산에송수신자의이름지정에따라 자동 (automatic) 또는명시적 (explicit) 버퍼링 : 복사또는참조에의한전송 고정크기메시지 / 가변크기메세지

3.4.2 message Passing Systems(cont.) 링크의논리적구현방법에의한분류 명몀 (Naming, 프로세스이름 ) 에의한분류 1) 직접통신 : 송 / 수진자의이름을외부적으로표현 send(p,msg), receive(q,msg) 기본연산자 대칭적주소지정방식 : 두프로세스가상대의이름을이용하여송수신» Send(P, message) : 프로세스 P 에게메시지보냄» Receive(Q, message) : 프로세스 Q 로부터메시지받음» 1:1 통신 ( 링크사용 ) 비대칭적주소지정방식 : 송신자만수신자의이름을사용» Send(P, message) : 프로세스 P 에게메시지 message 보냄» Receive(id, message) : 임의의프로세스로부터메시지 message 받음 id = 통신이일어난순간메시지를보낸프로세스의이름이자동으로설정됨» 1:n 또는 n:1 통신가능 ( 예, 수신자가송신자를굳이알필요가없을때 ) 통신링크의성질 단점 각프로세스쌍사이에는정확히하나의링크가존재 프로세스의쌍사이에링크가자동으로설정된다 ( 단지상대의고유명만으로 ) 양방향통신링크 프로세스정의의모듈성을제한 프로세스이름의변경은다른프로세스의정의의조사를필요로한다.

3.4.2 message Passing Systems(cont.) 2) 간접통신 : 프로세스또는시스템에포함된우편함 (mailbox) 을통한통신 프로세스가여러개의서로다른우편함을이용하여통신 기본연산자 send(a, message) : 메시지를우편함 A 로보냄 receive(a, message) : 우편함 A 로부터메시지수신함 통신링크의성질 한쌍의프로세스사이에공유우편함이있을때만링크가설정 한링크는 2 개이상의프로세스와관계 우편함은여러개의프로세스에의하여공유가능 단일또는양방향링크 수신프로세스의결정 1. 한링크에 2 개의프로세스만관계시키는방법 2. 한개의프로세스만수신자가되게하는방법 : 다수의송신가능 3. 시스템이송신자에게전송하는방법 개별프로세스의일부로우편함이소유되는경우 1. 송신자 ( 사용자 ) 는해당메일박스에송신하고 (send(p,msg)) 수신자는자기메일박스에서가져온다. (receive(msg)) 2. 프로세스간공유우편함을운용하는방법한프로세스가우편함 (A) 을선언하고소유자가되며이우편함의이름을아는프로세스들이이우편함을외부우편함으로선언한후에송 / 수신한다. send(a,msg), receive(a,msg) 소유자종료시메일박스삭제, 삭제사실을모든프로세스에게통지 우편함이운영체제에소유되는경우 1) OS 가우편함을생성, 3) 메시지의송수신, 4) 우편함삭제시킨다. 프로세스가우편함에대한소유권 ( 사용권 ) 을시스템호출에의하여얻은후송신자및수신자가되어송 / 수신한다.

3.4.2 message Passing Systems(cont.) 버퍼링 (Buffering) 에의한분류 링크의메시지보유용량 Zero capacity : rendez-vous(no buffering) 동기적통신 Bounded capacity : 유한길이큐이용 자동버퍼링 Unbounded capacity : 무한길이큐이용 자동버퍼링 메시지형태 고정크기 : 구현간단, 프로그림복잡 ( 원메세지를분해, 결합헤야 ) 가변크기 : 구현복잡, 프로그램간단 형태화된메시지 간접통신에만적용, 우편함에의존되는지정된형태 송신지연유무 무지연메시지송신 : 복사가아닌참조방식으로메세지전송 수신자로부터응답시까지대기후송신 : 메시지고정크기 (8 단어 )

3.4.2 message Passing Systems(cont.) 동기화 (Synchronization) Blocking-Synchronous Blocking send: 수신프로세스가메시지를받을때까지멈춤 Blocking receive: 메시지가있을때까지멈춤 Non-blocking asynchronous Nonblocking send: 메시지보내고다른연산계속 Nonblocking receive: 올바른메시지이거나널메시지이거나상관하지않고받음

3.5 Examples of IPC Systems - POSIX 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);

3.5.2 Examples of IPC Systems - Mach Mach communication is message based Even system calls are messages Each task gets two mailboxes at creation- Kernel and Notify Only three system calls needed for message transfer msg_send(), msg_receive(), msg_rpc() Mailboxes needed for communication, created via port_allocate()

3.5.3 Examples of IPC Systems Windows XP Message-passing centric via local procedure call (LPC) facility Only works between processes on the same system Uses ports (like mailboxes) to establish and maintain communication channels Communication works as follows: The client opens a handle to the subsystem s connection port object The client sends a connection request The server creates two private communication ports and returns the handle to one of them to the client The client and server use the corresponding port handle to send messages or callbacks and to listen for replies

3.5.3 Examples of IPC Systems Windows XP(cont.) Fig. 3.17 Local Procedure Calls in Windows XP

3.6 Communications in Client-Server Systems Sockets Remote Procedure Calls Remote Method Invocation (Java) 3.6.1 Sockets A socket is defined as an endpoint for communication Concatenation of IP address and port The socket 161.25.19.8:1625 refers to port 1625 on host 161.25.19.8 Communication consists between a pair of sockets

3.6.2 Remote Procedure Calls Remote procedure call (RPC) abstracts procedure calls between processes on networked systems Stubs client-side proxy for the actual procedure on the server The client-side stub locates the server and marshals the parameters The server-side stub receives this message, unpacks the marshaled parameters, and performs the procedure on the server

Execution of RPC Host Port From: client:kernel To :server:matachmaker Msg : address for RPC X From : server:matchmaker To : client:kernel msg : port P From : client:kernel To : client:p msg : <content> From : server:p To : client:kernel msg : <output>

3.6.2 Remote Method Invocation Remote Method Invocation (RMI) is a Java mechanism similar to RPCs RMI allows a Java program on one machine to invoke a method on a remote object

Assignment 1 socket 통신 (C#) Server Client Socket listener=new Socket( ) Socket sender=new Socket( ) listener.bind( 202.30.36.55:11000 ) listener.listen(10); sender.connect( 202.30.36.55:11000 ); Socket handler=listener.accept(); sender.send(msg); handler.receive(bytes) handler.send(msg); sender.receive(bytes)

1. using System; using System.Net; using System.Net.Sockets; using System.Text; public class SynchSocketServer { public static int Main(String[] args) 2. { 3. StartListening(); 4. return 0; 5. // Incoming data from the client. public static string data = null; public static void StartListening() { // Data buffer for incoming data. byte[] bytes = new Byte[1024]; Synch Socket Server-Client (C#) // Establish the local endpoint for the socket. // Dns.GetHostName returns the name of the // host running the application. IPHostEntry iphostinfo = Dns.Resolve(Dns.GetHostName()); IPAddress ipaddress = iphostinfo.addresslist[0]; IPEndPoint localendpoint = new IPEndPoint(ipAddress, 11000); // Create a TCP/IP socket. Socket listener = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 1. // Bind the socket to the local endpoint and listen for incoming connections. try { listener.bind(localendpoint); listener.listen(10); // Start listening for connections. while (true) { Console.WriteLine("\nServer is waiting for a connection..."); // Program is suspended while waiting for an incoming connection. Socket handler = listener.accept(); data = null; // An incoming connection needs to be processed. while (true) { bytes = new byte[1024]; int bytesrec = handler.receive(bytes); data += Encoding.ASCII.GetString(bytes, 0, bytesrec); if (data.indexof("<eof>") > -1) { break; // Show the data on the console. Console.WriteLine("Server received Text : {0", data); // Echo the data back to the client. byte[] msg = Encoding.ASCII.GetBytes(data); handler.send(msg); handler.shutdown(socketshutdown.both); handler.close(); catch (Exception e) { Console.WriteLine(e.ToString() ; Console.WriteLine("\nPress ENTER to continue..."); Console.Read();

Synch Socket Server-Client (C#) using System using System.Net; using System.Net.Sockets; using System.Text; public class SynchSocketClient { public static int Main(String[] args) { StartClient(); return 0; public static void StartClient() { // Data buffer for incoming data. byte[] bytes = new byte[1024]; // Connect to a remote device. try { // Establish the remote endpoint for the socket. // This example uses port 11000 on the local computer. IPHostEntry iphostinfo = Dns.Resolve(Dns.GetHostName()); IPAddress ipaddress = iphostinfo.addresslist[0]; IPEndPoint remoteep = new IPEndPoint(ipAddress,11000); // Create a TCP/IP socket. Socket sender = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ); // Connect the socket to the remote endpoint. Catch any errors. try { sender.connect(remoteep); Console.WriteLine("Socket connected to {0", sender.remoteendpoint.tostring()); // Encode the data string into a byte array. byte[] msg = Encoding.ASCII.GetBytes("This is a test<eof>"); // Send the data through the socket. int bytessent = sender.send(msg); // Receive the response from the remote device. int bytesrec = sender.receive(bytes); Console.WriteLine("Echoed test = {0", Encoding.ASCII.GetString(bytes,0,bytesRec)); // Release the socket. // sender.shutdown(socketshutdown.both); //sender.close(); Console.ReadKey(); catch (ArgumentNullException ane) { Console.WriteLine("ArgumentNullException : {0",ane.ToString()); catch (SocketException se) { Console.WriteLine("SocketException : {0",se.ToString()); catch (Exception e) { Console.WriteLine("Unexpected exception : {0", e.tostring()); catch (Exception e) { Console.WriteLine( e.tostring()); //try //try

Synch Socket Server-Client - Main (C#) using System.Diagnostics; using System.Threading; public class SynchronousSocketClient { public static void Main(String[] args) { string server = @"D:\WEBSITES\www.wins.or.kr\lecture\OS\2011-2\Programs\socket\SynckSocketServer\bin\Debug\SynckSocketServer.exe"; string client = @"D:\WEBSITES\www.wins.or.kr\lecture\OS\2011-2\Programs\socket\SocketClient\bin\Debug\SocketClient.exe"; Process pclient; Process pserver; pserver = Process.Start(server); Thread.Sleep(2000); pclient = Process.Start(client); Thread.Sleep(2000); pclient.kill(); pclient = Process.Start(client); Console.ReadKey();

Synch Socket Server-Client - 전체구조 (C#) Server.exe Main Socket listener = new Socket(...Tcp); listener.bind( IP# + Port # ); listener.listen(10); Socket handler = listener.accept(); handler.receive(msg); handler.send(msg); handler.shutdown(..); handler.close(); Client.exe Socket sender = new Socket(...Tcp); sender.connect( IP# + Port # ); sender.send(msg); sender.remoteendpoint sender.receive(bytes); sender.shutdown(..); sender.close(); Process pserver = Process.Start(server.exe); Process pclient = Process.Start(client.exe); Thread.Sleep(2000); pclient.kill(); pclient = Process.Start(client);

End of Chapter 3