Inter-Process Communication (IPC)
- Processes within a system may be independentor cooperating
- Independent process cannot affect or be affected by the execution of another process
- Cooperating process can affect or be affected by other processes, including sharing data
- Reasons for cooperating processes:
- Information sharing
- Computation speedup
- Modularity
- Convenience
- Cooperating processes require an IPC mechanism that will allow them to exchange data
- Two fundamental models of IPC:
- Message passing & Shared memory
- 시스템 내 프로세스는 독립적이거나 협력적일 수 있다.
- 독립 프로세스는 다른 프로세스의 실행에 영향을 미치거나 영향을 받을 수 없습다.
- 협력 프로세스는 데이터 공유를 포함한 다른 프로세스에 영향을 미치거나 영향을 받을 수 있다.
- 프로세스를 협력해야 하는 이유:
- 협력 프로세스에는 데이터를 교환할 수 있는 IPC 메커니즘이 필요합니다.
- IPC의 두 가지 기본 모델:
시스템 내 프로세스는 독립적이거나 협력적
협력해야 하는 이유는 다음과 같다.
협력 프로세스에는 IPC 메커니즘이 필요하다.
두 가지 기본 모델: Message Passing & Shared Memory
Two Fundamental IPC Models
Message-passing model
- Useful in a distributed environment
- Typically implemented using system calls, thus requiring the more time-consuming task of kernel intervention
- Two key operations: send(message) & receive(message)
- 분산 환경에서 유용
- 일반적으로 시스템 호출을 사용하여 구현되므로 커널 개입의 더 많은 시간이 소요됩니다.
- 두 가지 주요 작업: 송신(메시지) 및 수신(메시지)
![](https://velog.velcdn.com/images/dahyeon/post/763094a1-ddc3-42f6-86cc-edf182810de5/image.png)
Message-passing model: 프로세스 간 교환되는 메시지를 통해 통신이 이루어진다.
분산 환경에서 유용하다. 시스템 호출을 사용해서 커널 개입에 더 많은 시간이 소요된다.
Message Passing
- Producer-consumer becomes trivial
- Processes need to:
- 1) Establish a communication link between them
- 2) Exchange messages via send/receive methods
- 생산자-소비자가 사소한 존재가 됨
- 프로세스의 필요성:
- 1) 상호간의 커뮤니케이션 링크 구축
- 2) 송수신 방법을 통한 메시지 교환
![](https://velog.velcdn.com/images/dahyeon/post/2336bd6c-cd68-4b54-8068-ce9907694e5c/image.png)
생산자 소비자가 사소해진다. 프로세스가 필요하다.
Shared-memory model
-
Cooperating processes establish a region of shared memory and then they can exchange information by reading and writing data in the shared areas
-
협력 프로세스는 공유 메모리 영역을 설정한 다음 공유 영역에서 데이터를 읽고 쓰는 방식으로 정보를 교환할 수 있다.
협력 프로세스는 공유 메모리 영역을 설정하고 공유 영역에서 데이터를 읽고 쓴다.
- Typically, a shared memory region resides in the address space of the process creating the shared-memory segment
- Faster than message passing because system calls are required only to establish shared memory regions.
- Once established, all accesses are treated as routine memory accesses, and no assistance from kernel is required
- 일반적으로 공유 메모리 영역은 공유 메모리 세그먼트를 생성하는 프로세스의 주소 공간에 상주한다.
- 공유 메모리 영역을 설정하기 위해서만 시스템 호출이 필요하기 때문에 메시지 전달 속도보다 빠르다.
- 일단 설정되면 모든 액세스는 일상적인 메모리 액세스로 처리되며 커널의 도움이 필요하지 않다.
공유 메모리 영역 -> 공유 메모리 세그먼트를 생성하는 프로세스의 주소 공간.
메모리 영역을 설정하기 위해서만 시스템 호출이 필요해서 메시지 전달 속도보다 빠르다.
- The communication here is under the control of the users’ processes, not under the OS’s control
- Major issue is how to provide mechanism that will allow the user processes to synchronize their actions when they access shared memory
- 여기서의 통신은 OS의 제어가 아닌 사용자의 프로세스의 제어 하에 있다.
- 주요 문제는 사용자 프로세스가 공유 메모리에 액세스할 때 작업을 동기화할 수 있는 메커니즘을 제공하는 방법이다.
통신은 사용자 프로세스의 제어. 동기화할 수 있는 메커니즘을 제공해야 한다.
![](https://velog.velcdn.com/images/dahyeon/post/d666505e-5a79-4de8-85e0-d9525ba1feec/image.png)
Shared Memory
- POSIX Shared Memory
- Process first creates shared memory segment
- shm_fd= shm_open(name, O_CREAT | O_RDWR, 0666);
- Also used to open an existing segment to share it
- Set the size of the segment
- Map the shared memory segment to a specific memory region
- ptr= mmap(0, size, PROT_WRITE, MAP_SHARED, shm_fd, 0);
- Now the process could write to the shared memory
- sprintf(ptr, "Writing to shared memory");
- POSIX 공유 메모리
- 프로세스에서 먼저 공유 메모리 세그먼트 생성
- shm_create=shm_open(name, O_CREATE | O_RDWR, 0666);
- 기존 세그먼트를 열어 공유하는 데도 사용된다.
- 세그먼트 크기 설정
- ftruncate(shm_nots, 4096);
- 공유 메모리 세그먼트를 특정 메모리 영역에 매핑
- ptr=mmap(0, size, PRO_WRITE, MAP_SHARED, shm_map, 0);
- 이제 프로세스가 공유 메모리에 쓸 수 있다.
- sprintf(ptr, "Writing to shared memory");
메모리 세그먼트 생성 : shm_open
세그먼트 크기 설정: ftruncate
특정 메모리 영역에 매핑: ptr = mmap (중요)
공유 메모리에 쓰기 : sprintf
- IPC POSIX Producer
![](https://velog.velcdn.com/images/dahyeon/post/100ee3ac-5f03-4f75-9de1-93699c4b1167/image.png)
shm_open
fruncate
ptr = mmap
sprintf
- IPC POSIX Consumer
![](https://velog.velcdn.com/images/dahyeon/post/7e4690af-934b-4315-b561-5b47d0889b90/image.png)
shm_open
mmap
printf (read from the shared memory)
shm_unlink
What about IPC in Linux?
- Linux provides a rich environment for processes to communicate with each other
- A mechanismfor notifying a process about a particular event occurrence
- Several mechanisms for passing data among processes
- Shared memory
- Message queue (= message passing)
- Pipes
- A set of networking facilities
- Linux는 프로세스가 서로 통신할 수 있는 풍부한 환경을 제공한다.
- 프로세스에 특정 이벤트 발생을 알리는 메커니즘
- 프로세스 간에 데이터를 전달하는 몇 가지 메커니즘
- Shared memory
- Message queue (= message passing)
- Pipes
- A set of networking facilities
linux 상에서 프로세스가 통신하는 환경
특정 이벤트 발생 알림: signal
데이터 전달: shared memory, message queue, pipes, a set of networking gacilities
Signals
- A IPC mechanism to notify a process of a particular event
- Can be synchronous (e.g., illegal memory access) or asynchronous (e.g., killed)
- Can be thought as a software interrupt
- Signal is generated by particular events
- Signal is delivered to the process
- A signal handler processes the signal
- Every signal has a default handler that kernel runs when handling signal
- User-defined signal handler can override the default
- 프로세스에 특정 이벤트를 알리는 IPC 메커니즘
- 동기식(예: illegal memory access) 또는 비동기식(예: killed)일 수 있습니다.
- software interrupt으로 생각할 수 있다.
- 신호는 특정 이벤트에 의해 생성된다.
- 신호가 프로세스로 전달된다.
- signal handler가 신호를 처리한다.
- 모든 신호에는 신호를 처리할 때 커널이 실행되는 기본 처리기가 있다.
- 사용자 정의 신호 처리기가 기본값을 재정의할 수 있다.
signal은 특정 이벤트를 알리는 IPC 메커니즘. software interrupt로 생각할 수 있다.
Signal Handling
- A process can define a signal handler for a signal
![](https://velog.velcdn.com/images/dahyeon/post/1b8f9edf-fa42-47f4-a983-cd60f9f548a6/image.png)
- A process can send a signal to other process
- int kill(pid_tpid, int sig);
- The signal handler is invoked on the target process
- 프로세스는 신호에 대한 signal handler를 정의할 수 있다.
- 프로세스가 다른 프로세스로 신호를 보낼 수 있다.
- int kill(pid_tpid, int sig);
- signal handler가 target 프로세스에서 호출된다.
signal handler. 프로세스가 다른 프로세스로 신호를 보낼 수 있는데, kill은 signal을 보내기 위한 function이다. signal handler는 target 프로세스에서 호출된다.
$ man 7 signal
![](https://velog.velcdn.com/images/dahyeon/post/594b4bf4-aedf-4ea8-b5e9-e1cec4b45dd2/image.png)
Pipes
- A pipe acts as a conduit allowing two processes to communicate
- Pipes can be accessed using ordinary read() and write() system calls as UNIX treats a pipe as a special type of files
- e.g., The output of one process can be directed into the input of another process by using a pipe (I/O redirection)
- Two common types of pipes used on both UNIX/Linux and Windows systems
- Ordinary pipe VS. Named pipe
- 파이프는 두 프로세스가 통신할 수 있는 통로 역할을 한다.
- UNIX가 파이프를 특수 유형의 파일로 처리하기 때문에 일반적인 read() 및 write() 시스템 호출을 사용하여 파이프에 액세스할 수 있다.
- 예를 들어 파이프를 사용하여 한 프로세스의 출력을 다른 프로세스의 입력으로 유도할 수 있다(I/O 리디렉션).
- UNIX/리눅스 및 윈도우즈 시스템에서 모두 사용되는 두 가지 일반적인 유형의 파이프
파이프는 프로세스가 통신할 수 있는 통로이다. read(), write()로 파이프에 액세스할 수 있다.
- Ordinary pipes:allowing only one-way communication (= unidirectional) and requiring parent-child relationship between communicating processes
- Producer writes to one end (the write-end of the pipe)
- Consumer reads from the other end (the read-end of the pipe)
- Ordinary pipes are therefore unidirectional
- pipe(int fd[])
- 일반 파이프: 단방향 통신만 가능하며(= 단방향) 통신 프로세스 간에 부모-자녀 관계가 필요
- 생산자가 한쪽 끝에 쓰기(파이프의 쓰기 끝)
- 다른 쪽 끝에서 전기 소비 장치 판독값(파이프의 판독값)
- 따라서 일반 파이프는 단방향이다.
- pipe(int fd[])
Ordinary pipe: 단반향 통신. 부모-자녀 관계 필요.
![](https://velog.velcdn.com/images/dahyeon/post/d52a2ee8-2a4f-4a94-988c-2ff3850e552e/image.png)
Ordinary pipe in Linux
![](https://velog.velcdn.com/images/dahyeon/post/6da6c0d9-fd93-41a8-a88c-c56041ef6be8/image.png)
![업로드중..]()
한 쪽에서 읽고 한 쪽에서 쓴다.
Pipes
- Named pipes:
- More powerful than ordinary pipes
- Communication is bidirectional
- No parent-child relationship is necessary between the communicating processes
- Several processes can use the named pipe for communication
- Named pipes stay alive even after process terminates
- 명명된 파이프:
- 일반 파이프보다 강력하다.
- 통신은 양방향이다.
- 통신 프로세스 간에 부모-자녀 관계가 필요하지 않다.
- 여러 프로세스에서 명명된 파이프를 통신에 사용할 수 있다.
- 명명된 파이프는 프로세스가 종료된 후에도 활성 상태를 유지한다.
named pipe: 양방향 통신. 부모-자식 x. 여러 프로세스가 동시에 통신. 프로세스 종료 후에도 활성 상태 유지.
Network Structure
- Internally, networking in the Linux kernel is implemented by 3 components:
- The socket interface
- Protocol stack (TCP/IP protocol suite)
- The IP protocol implements routing between different hosts anywhere on the network
- On top of the IP protocol are built the UDP or TCP protocols
- Network-device drivers
- Ethernet, WiFi, Bluetooth, etc.
- 내부적으로 리눅스 커널의 네트워킹은 세 가지 구성 요소에 의해 구현된다:
- 소켓 인터페이스
- 프로토콜 스택(TCP/IP 프로토콜 제품군)
- IP 프로토콜은 네트워크의 다른 호스트 간 라우팅을 구현한다.
- IP 프로토콜 위에 UDP 또는 TCP 프로토콜이 구축된다.
- 네트워크 장치 드라이버
linux kernel 네트워킹 3 components:
socket interface
protocal stack (TCP/IP)
network-device drivers: Ethernet, WiFi, Bluetooth...
![](https://velog.velcdn.com/images/dahyeon/post/698d5fe0-2b08-4094-b76d-b93ee0c35abb/image.png)
UDP vs. TCP
![](https://velog.velcdn.com/images/dahyeon/post/960043d8-d9b8-4ca9-abfe-8d128587f052/image.png)
- UDP (User Datagram Protocol)
- Unreliable
- Since there are no guarantees of delivery, some packets may become lost
- Packets may also be received out-of-order
- Fast transmission
- UDP(사용자 데이터그램 프로토콜)
- 신뢰할 수 없음
- 전달에 대한 보장이 없기 때문에 일부 패킷이 손실될 수 있다.
- 패킷이 잘못 수신될 수도 있다.
- 고속 전송
UDP
신뢰 x: 포트 넘버만 지정.
1) packet의 전송을 보장하지 못한다.
2) out of order
고속
![](https://velog.velcdn.com/images/dahyeon/post/1080b1e3-80ba-4f94-ac0e-38aded6f1e69/image.png)
- TCP (Transmission Control Protocol)
- Reliable & in-order
- Whenever host sends packet, the receiver must send an acknowledgement packet (ACK). If ACK is not received before a timer expires, sender will resend.
- Sequence numbers in packets allow receiver to sort packets in order and notice missing packets.
- Slower speed than UDP
- 전송 제어 프로토콜
- 안정적이고 질서정연한
- 호스트가 패킷을 보낼 때마다 수신기는 ACK(확인 패킷)를 전송해야 한다. 타이머가 만료되기 전에 ACK가 수신되지 않으면 보낸 사람이 다시 전송한다.
- 패킷의 시퀀스 번호를 사용하면 수신기가 패킷을 순서대로 정렬하고 누락된 패킷을 알 수 있다.
- UDP보다 느린 속도
TCP
reliable & in-order
ACK: 확인 패킷 전송, 수신 확인 안될 시 다시 전송
Sequence number: 수신기가 정렬, 누락 패킷 확인
느린 속도
Communication in Client-Server Systems
- Client-Server Computing Systems
- A specialized distributed system in which server systems satisfy requests generated by clients
- Most network process communications follow a client-server model
- A process on one computer acts as a server, and a process on another computer acts as a client
- Two strategies for communication in client-server systems
- Sockets
- Remote Procedure Calls(RPC)
- 클라이언트-서버 컴퓨팅 시스템
- 서버 시스템이 클라이언트에 의해 생성된 요청을 충족하는 특수 분산 시스템
- 대부분의 네트워크 프로세스 통신은 클라이언트-서버 모델을 따른다.
- 한 컴퓨터의 프로세스가 서버 역할을 하고 다른 컴퓨터의 프로세스가 클라이언트 역할을 한다.
- 클라이언트-서버 시스템의 통신을 위한 두 가지 전략
![업로드중..]()
Sockets
- A socket is defined as an endpoint for communication
- A pair of processes communicating over a network employs a pair of sockets (one for each process)
- Each socket is associated with an unique combination of IP address and port
- The socket 161.25.19.8:1625 refers to port 1625 on host 161.25.19.8
- 소켓은 통신을 위한 엔드포인트로 정의된다.
- 네트워크를 통해 통신하는 한 쌍의 프로세스는 한 쌍의 소켓(각 프로세스마다 하나씩)을 사용한다.
- 각 소켓은 IP 주소 및 포트의 고유한 조합과 연결된다.
- 소켓 161.25.19.8:1625는 호스트 161.25.19.8의 포트 1625를 참조한다.
소켓: 통신을 위한 endpoint
한 쌍의 프로세스는 한 쌍의 소켓 (프로세스마다 하나씩)을 사용한다.
![](https://velog.velcdn.com/images/dahyeon/post/725b2ab2-c06d-4006-bcf7-60d0ab98ec91/image.png)
- A server opens up a specified port for listening & waits for incoming client requests.
- Once a request is received, the server accepts a connection from the client socket to complete the connection
- All connections must be unique, meaning that they consist of a unique pair of sockets!
- All ports below 1024 are well known, used for standard services
- Servers implementing specific services listen to well-known ports (e.g., Web/HTTP server: port 80, FTP server: port 21, SSH server: port 22)
- A client initiating a request for a connection is assigned a port by its OS.
- This local port has some arbitrary number greater than 1024
- 서버는 수신 대기를 위해 지정된 포트를 열고 수신 클라이언트 요청을 기다린다.
- 요청이 수신되면 서버는 클라이언트 소켓에서 연결을 승인하여 연결을 완료한다.
- 모든 연결은 고유해야 한다. 즉, 고유한 소켓 쌍으로 구성된다!
- 1024 미만의 모든 포트는 잘 알려져 있으며 표준 서비스에 사용된다.
- 특정 서비스를 구현하는 서버는 잘 알려진 포트(예: 웹/HTTP 서버: 포트 80, FTP 서버: 포트 21, SSH 서버: 포트 22)를 수신한다.
- 연결 요청을 시작하는 클라이언트는 해당 OS에 의해 포트가 할당된다.
- 이 로컬 포트의 일부 임의 번호가 1024보다 크다.
unique pair of sockets
1024 미만의 포트는 잘 알려져 있다.
해당 OS에 의해 포트가 할당된다.
Socket Programming in C/C++
- Unix-like OS tries to interact with devices, file, and networks in a uniform fashion
- OS treats them all as part of the file system
- Socket system calls are used for inter-process communication over a network
- 3 steps (connect, send/receive data, terminate), similar to the basic file I/O (open, read/write, close)
- Berkeley Sockets serve to implement this abstraction for network communication
- Unix와 유사한 OS는 장치, 파일 및 네트워크와 동일한 방식으로 상호 작용한다.
- OS는 이 모든 것을 파일 시스템의 일부로 취급한다.
- 소켓 시스템 호출은 네트워크를 통한 프로세스 간 통신에 사용된다.
- 기본 파일 I/O와 유사한 3단계(연결, 데이터 송수신, 종료)(열기, 읽기/쓰기, 닫기)
- Berkeley Sockets는 네트워크 통신을 위해 이 추상화를 구현하는 역할을 한다.
소켓 시스템 호출은 프로세스간 통신에 사용된다.
Barkeley Socket은 추상화를 구현하는 역할을 한다.
![](https://velog.velcdn.com/images/dahyeon/post/da11c43f-32f7-475f-8073-e4a06fd47b44/image.png)
Berkeley Sockets Example (TCP Server)
![](https://velog.velcdn.com/images/dahyeon/post/1cb60354-dc3f-4f3a-b610-e5644b70c497/image.png)
create socket
set ip address and port number
associate(open) socket
wait client
if client connect, allow connection
socket()
- The socket() system call has 3 arguments: Domain, Communication types, Protocol
- Domain of communication
- The Internet domain: AF_INET or PF_INET for IPv4, AF_INET6 or PF_INET6 for IPv6
- The UNIX domain: AF_UNIX or PF_UNIX or AF_LOCAL or PF_LOCAL
- Types of communication
- SOCK_STREAM : TCP/IP
- SOCK_DGRAM : UDP/IP
- socket() 시스템 호출에는 세 가지 인수가 있다. 도메인, 통신 유형, 프로토콜
- 통신 영역
- 인터넷 도메인: IPv4의 경우 AF_INET 또는 PF_INET, IPv6의 경우 AF_INET6 또는 PF_INET6
- UNIX 도메인: AF_UNIX 또는 PF_UNIX 또는 AF_LOCAL 또는 PF_LOCAL
- 커뮤니케이션의 종류
- SOCK_STREAM : TCP/IP
- SOCK_DGRAM : UDP/IP
socket 시스템 호출 3 arguments: Domain, Communication types, Protocol
![](https://velog.velcdn.com/images/dahyeon/post/61dacc1a-6616-49e6-9cc1-ec6245f99acc/image.png)
- A socket provides an integer identifier through which a network communication is going to take place. The newly created socket is analogous to a telephone that has not yet been used to place a call; the socket identifier has not yet been used to connect to anything
- 소켓은 네트워크 통신이 이루어질 정수 식별자를 제공한다. 새로 생성된 소켓은 아직 전화를 걸기 위해 사용되지 않은 전화와 유사합니다. 소켓 식별자는 아직 어떤 것에도 연결하기 위해 사용되지 않았다.
![](https://velog.velcdn.com/images/dahyeon/post/08e204e9-00cf-4ac8-8b37-da233722225c/image.png)
bind()
- A server will typically bind the socket, defining the IP and port on which it will listen for connection
- The struct sockaddr_inholds information about how the socket will be used
- 서버는 일반적으로 소켓을 바인딩하여 연결을 수신할 IP와 포트를 정의한다.
- 구조 sockaddr_in은 소켓이 어떻게 사용될 것인지에 대한 정보를 보유하고 있다.
socket을 bind하여 연결을 수신할 ip와 port를 정의한다.
sockaddr_in은 소켓 사용법에 대한 정보를 보유한다.
![](https://velog.velcdn.com/images/dahyeon/post/6baa1297-8328-4268-915d-4caba7bdba50/image.png)
listen()
- After binding, a server may call listen() to await communication
- int listen(int sockfd, int backlog)
- -> The 2nd parameter, backlog, describes how many connections can be queued (5 in the example below) while the server is handling another communication. An error value (-1) will be returned to additional clients trying to connect.
- 바인딩 후 서버가 listen()을 호출하여 통신을 기다릴 수 있다.
- int listen(int sockfd, int backlog)
- -> 두 번째 매개변수인 backlog는 서버가 다른 통신을 처리하는 동안 대기열에 넣을 수 있는 연결 수(아래 예제에서는 5개)를 설명한다. 연결을 시도하는 추가 클라이언트에 오류 값(-1)이 반환된다.
![](https://velog.velcdn.com/images/dahyeon/post/f63c206b-2ebe-4914-babe-ec9d474d0031/image.png)
accept()
- Once a server has received an incoming connect attempt, it can accept the connection
- accept() returns a second socket on which data will be transmitted. This allows the original socket to continue to listen for additional connections
- int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen)
- 서버가 수신 연결 시도를 수신하면 연결을 승인할 수 있다.
- accept()는 데이터가 전송될 두 번째 소켓을 반환한다. 이를 통해 원래 소켓이 추가 연결을 계속 수신할 수 있다.
- int accept(int sockfd, 구조 sockaddr *addr, socklen_t *addrlen)
accept()는 데이터가 전송될 두 번째 소켓 반환
![](https://velog.velcdn.com/images/dahyeon/post/613150a8-7265-451f-95c3-dae28f897735/image.png)
connect()
- A client performs a step similar to binding, but instead of listening, it actively makes a call, establishing a connection
- The connect() is used to call the server in an attempt to establish a connection
- 클라이언트는 바인딩과 유사한 단계를 수행하지만 listen 대신 능동적으로 call를 수행하여 연결을 설정한다.
- connect()는 연결을 설정하기 위해 서버를 호출하는 데 사용됩니다.
![](https://velog.velcdn.com/images/dahyeon/post/9041daab-2eb4-4e60-8327-0d2f35e33ba4/image.png)
send() & receive()
- After a connection has been established between the client and server, data can be transmitted and received
- The send() system call takes 4 arguments: Socket identifier, Address pointing to data, Number of bytes to send, Flag setting
- ssize_tsend(int sockfd, const void *buf, size_tlen, int flags)
- The recv() also takes 4 arguments: Socket identifier, Address pointing to data, Max Number of bytes to receive, Flag setting
- ssize_trecv(int sockfd, void *buf, size_tlen, int flags)
- Both the server and client can execute send() and recv()
- The send() and recv() functions are similar to the fread() and fwrite() functions in that the arguments define an address and a number of bytes, rather than the type of data at the given address
- 클라이언트와 서버 간에 연결이 설정된 후 데이터를 송수신할 수 있습니다.
- send() 시스템 호출에는 4개의 인수가 사용된다. 소켓 식별자, 데이터를 가리키는 주소, 보낼 바이트 수, 플래그 설정
- ssize_tsend(int sockfd, constvoid *buf, size_tlen, int 플래그)
- recv()는 또한 4개의 인수를 사용한다. 소켓 식별자, 데이터를 가리키는 주소, 수신할 최대 바이트 수, 플래그 설정
- ssize_trecv(int sockfd, void *buf, size_tlen, int 플래그)
- 서버와 클라이언트 모두 send() 및 recv()를 실행할 수 있다.
- send() 및 recv() 함수는 fread() 및 fwrite() 함수와 유사하다. 인수는 지정된 주소의 데이터 유형이 아닌 주소와 바이트 수를 정의한다.
Example Codes for send() & receive()
![](https://velog.velcdn.com/images/dahyeon/post/cfe34eda-2865-4aed-9b07-7f94ae7add06/image.png)
close()
- Once communication is finished, both the server and client should close their respective sockets
- A close() system call initiates a series of operations within the OS to terminate the connection
- Thus, the socket may still appear in a netstatprogram listing for several seconds, until the OS has finished the close
- 통신이 완료되면 서버와 클라이언트가 각각의 소켓을 닫아야 한다.
- close() 시스템 호출은 OS 내에서 연결을 종료하는 일련의 작업을 시작한다.
- 그러므로 소켓은 OS가 닫기를 완료할 때까지 몇 초 동안 netstat 프로그램 목록에 계속 나타날 수 있다.
![](https://velog.velcdn.com/images/dahyeon/post/0bc70d10-5141-45bd-a75d-68995ee4befe/image.png)
Server Example
![](https://velog.velcdn.com/images/dahyeon/post/13068a23-50a3-4ee0-afee-723aeddae25f/image.png)
![](https://velog.velcdn.com/images/dahyeon/post/b619db84-ef84-420f-a0ab-0dad071c3992/image.png)
![](https://velog.velcdn.com/images/dahyeon/post/01a3d73f-d9b6-47d3-975e-f9cea3250871/image.png)
Client Example
![](https://velog.velcdn.com/images/dahyeon/post/5d056a15-e6a4-49b1-96a7-4aff69c07d84/image.png)
![](https://velog.velcdn.com/images/dahyeon/post/5338010a-b3a7-470a-a80e-2fc3e5e63409/image.png)
Sockets versus RPCs
- Communication using sockets (although common and efficient) is considered a low-level form of communication between distributed processes
- Why? … because sockets allow only an unstructured stream of bytes to be exchanged between the communicating threads. It is the responsibility of the client or server application to impose a structure on the data
- Now, lets look a higher-level method of communication: Remote procedure calls (RPCs)
- One of the most common forms of remote service
- A way to abstract procedure calls between processes on networked systems
- Not only useful for client-server computing, but Android also uses remote procedures as a form of IPC(Inter-process Communication) between processes running on the same system
- 소켓을 사용한 통신(일반적이고 효율적이긴 하지만)은 분산 프로세스 간의 저수준 통신 형태로 간주된다.
- 왜일까? … 소켓은 통신 스레드 간에 구조화되지 않은 바이트 스트림만 교환할 수 있기 때문이다. 데이터에 구조를 적용하는 것은 클라이언트 또는 서버 애플리케이션의 책임이다.
- 이제 고급 통신 방법: 원격 프로시저 호출(RPC)을 살펴볼 것이다.
- 가장 일반적인 형태의 원격 서비스 중 하나
- 네트워크 시스템에서 프로세스 간의 프로시저 호출을 추상화하는 방법
- 클라이언트-서버 컴퓨팅에 유용할 뿐만 아니라 Android는 동일한 시스템에서 실행되는 프로세스 간 IPC(Inter-Process Communication)의 한 형태로 원격 프로시저를 사용합니다.
소켓: 저수준 통신 형태. 스레드 간에 구조화되지 않은 바이트 스트림만 교환할 수 있어서.
RPC: 고급 통신 방법. 프로세스 간의 procedure call을 추상화. android는 ipc의 한 형태로 rpc 사용.
Remote Procedure Calls
![](https://velog.velcdn.com/images/dahyeon/post/9b5efa27-b132-4983-95e1-13b9b993e2df/image.png)
Remote Procedure Calls (RPCs)
- The semantics of RPCs allows a client(= caller) to invoke a procedure on a remote host(= callee/server) as it would invoke a procedure locally
- The RPC system hides the details that allow communication to take place by providing stubs on the server / client sides
- Stubs are proxy objects that abstracts the actual procedure on the server side
- The Client-side stub locates the server and marshallsthe parameters
- Packaging parameters into a form for transmission on network
- The server-side stub receives this message, unpacks the marshalled parameters (unmarshalling), and performs the procedure on the server
- RPC의 의미론은 클라이언트(= 호출자)가 로컬에서 프로시저를 호출하는 것처럼 원격 호스트(= 호출자/서버)에서 프로시저를 호출할 수 있게 한다.
- RPC 시스템은 서버/클라이언트 측에 스텁을 제공하여 통신이 이루어지도록 하는 세부 정보를 숨긴다.
- Stubs는 서버 측의 실제 절차를 추상화하는 프록시 개체이다.
- The Client-side stub은 서버를 찾고 매개 변수를 마샬링한다.
- 네트워크에서 전송하기 위한 형식으로 매개 변수 패키징
- The server-side stub는 이 메시지를 수신하고, 마샬링된 매개 변수의 압축을 풀고(unmarshalling), 서버에서 절차를 수행합니다.
server에서 procedure 호출 가능.rpc 시스템은 server/client 측에 stub 제공, 통신 세부 정보 숨김.
stubs는 프록시 개체. client stub에서는 매개 변수 마샬링. server stub에서는 마샬링 매개 변수 압축을 풀고 서버에서 절차 수행.
![](https://velog.velcdn.com/images/dahyeon/post/4d33b0bf-c841-4741-8acd-2a663da19cc9/image.png)