chapter 3 : processes - iispl() processes-1.pdf · sockets, rpc, rmi(java) socket program...

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

Upload: others

Post on 23-Mar-2020

18 views

Category:

Documents


0 download

TRANSCRIPT

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는 각 프로세스의 상태 및 관리를 위한 정보가 표현되는 자료구조이다.

Solaris 10 Unix: /usr/include/sys/proc.h (99행) Fedora Linux: /usr/src/kernels/linux-2.6.35.6/include/linux/sched.h (1167행)

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

3.1 Process Concept(cont.)

Fig. 3.3 Process Control Block (PCB)

• PCB와 프로세스 • 프로세스의 생성시 :

• OS가 프로세스를 위하여 PCB의 메모리를 할당한다.

• OS가 PCB를 초기화한다. • OS가 해당큐에 PCB를 배치한다.

• 프로세스가 활성화 상태에서 OS는 PCB를 해당 큐로 이동 시킨다.

• 프로세스의 종료시 OS가 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.8 Addition of Medium Term Scheduling to queueing diagram

Fig 3.7 Queueing-diagram representation of process scheduling

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

Fig. 3.9 A tree of process on typical Solaris system

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

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 */ } }

Fig. 3.10 Creating a separate process using the UNIX fork() system call

• 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);

Unix fork()로 프로세스 생성하는 C 코드

3.3 Operations on Process(cont.)

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

Unix fork()로 프로세스 생성하는 C 코드

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에서)

…. if(pid==0) pid=fork(); x=10000;

pid x : 10000 parent data

parent code

pid=40

xs esp

eip=100 eax= …0

memory parent task_nion

(pcb)

…. if(pid==0) pid=fork(); x=10000;

pid x : 10000

child data

parent data

parent/child code

pid=40

ss

esp eip=100 eax=41

memory parent task_nion

(pcb)

pid x : 10000

pid=41

ss

esp eip=100 eax=0

…0

child task_nion

(pcb)

… 101 100 99 …

Figure a. fork() 실행전 Figure b. fork() 실행후

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)

Kernel mode stack task_struct

3.3 Operations on Process(cont.)

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

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

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

Result s :

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; 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 () ); }

$ cat myexit.c #include <stdio.h> main () { printf ("I'm going to exit with return code 77\n"); exit (77); }

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 )이 필요 하다.

공유메모리, 메시지 매핑 협조의 필요성

정보 공유 (information sharing) 계산 속도 증가 (computation speedup) : parallel computing으로 모듈화(modularity) 편이성(convenience) : parallel computing으로

예 생산자 소비자 문제

IPC의 두 모델 공유메모리(Shared Memory) 메세지전달(Message Passing)

CPU

Memory

P1

P2

CPU

Memory

P3

Shared Memory

OS

OS

port Post office mailbox

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) 생산자-소비자 문제 버퍼가 꽉 차 있으면 생산자가 대기, 버퍼가 비어 있으면 소비자가 대기

유한 버퍼 생산자-소비자 문제(bounded-buffer producer-consumer problem) 스레드(LWP)로 처리하면 효과적이다 방법1: 공유 메모리를 이용한 방법(3.4.1절) 방법 2: 메시지 전달을 이용한 방법(3.4.2절) 방법3: 세마포어를 이용한 방법(6.6.1절) 방법4: 세마포어와 스레드를 이용한 방법 (6장 프로젝트 p266)

Memory

P1

P2

Shared Memory

Compiler (producer)

Assembler (consumer)

kernel

Assembly code

3.4.1 Shared-Memory Systems(cont.)

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

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 int out = 0; //used by consumer

synchronization

synchronization

IPC - 3.4.2 message Passing Systems

h/w

Memory

P

h/w

Memory

Q

kernel kernel

No shared memory between 2 processes

Just wires (bus or network)

Ask OS to send message – IPC system call

Send(host, process, message) – Direct

Send(host, port #) - Indirect Let Post-office(OS) provide mailbox code program using mailbox # (port)

Do you know his PID (at coding time)? What if that his PID changes after coding?

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

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>

Host Port

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)

Synch Socket Server-Client (C#) 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]; // 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 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.RemoteEndPoint

sender.Send(msg); sender.Receive(bytes); sender.Shutdown(..); sender.Close(); Main

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