제12장 프로세스 사이의 통신.

Slides:



Advertisements
Similar presentations
Sockets: Network IPC Internet Socket UNIX Domain Socket.
Advertisements

Networks: TCP/IP Socket Calls1 Elementary TCP Sockets Chapter 4 UNIX Network Programming Vol. 1, Second Ed. Stevens.
Sockets Basics Conectionless Protocol. Today IPC Sockets Basic functions Handed code Q & A.
Tutorial 8 Socket Programming
CS 311 – Lecture 18 Outline IPC via Sockets – Server side socket() bind() accept() listen() – Client side connect() Lecture 181CS Operating Systems.
Socket Addresses. Domains Internet domains –familiar with these Unix domains –for processes communicating on the same hosts –not sure of widespread use.
Today’s topic Inter-process communication with pipes.
Networking S04, Recitation, Section A
Sockets CIS 370 Fall 2009, UMassD. Introduction  Sockets provide a simple programming interface which is consistent for processes on the same machine.
TCP Socket Programming. r An abstract interface provided to the application programmer  File descriptor, allows apps to read/write to the network r Allows.
Sockets and intro to IO multiplexing. Goals We are going to study sockets programming as means to introduce IO multiplexing problem. We will revisit socket.
1 Networking (Stack and Sockets API). 2 Topic Overview Introduction –Protocol Models –Linux Kernel Support TCP/IP Sockets –Usage –Attributes –Example.
Operating Systems Chapter 9 Distributed Communication.
Assignment 3 A Client/Server Application: Chatroom.
Elementary TCP Sockets
CS345 Operating Systems Φροντιστήριο Άσκησης 2. Inter-process communication Exchange data among processes Methods –Signal –Pipe –Sockets.
9/12/2015B.R1 Socket Abstraction and Interprocess Communication B.Ramamurthy CSE421.
Sockets CIS 370 Lab 10 UMass Dartmouth. Introduction 4 Sockets provide a simple programming interface which is consistent for processes on the same machine.
Computer Systems II CSC 2405 Network Programming.
Server Sockets: A server socket listens on a given port Many different clients may be connecting to that port Ideally, you would like a separate file descriptor.
Shell (Part 2). Example r What if we want to support something like this: m ps –le | sort r One process should execute ps –le and another should execute.
System Commands and Interprocess Communication. chroot int chroot(const char *path); chroot changes the root directory to that specified in path. This.
Pipes A pipe is a simple, synchronized way of passing information between processes A pipe is a special file/buffer that stores a limited amount of data.
CS252: Systems Programming Ninghui Li Based on Slides by Prof. Gustavo Rodriguez-Rivera Topic 8: Opening Files and Starting Processes.
Chapter 6 UNIX Special Files Source: Robbins and Robbins, UNIX Systems Programming, Prentice Hall, 2003.
Remote Shell CS230 Project #4 Assigned : Due date :
Networking Tutorial Special Interest Group for Software Engineering Luke Rajlich.
An Introductory 4.4BSD Interprocess Communication Tutorial Stuart Sechrest.
CE Operating Systems Lecture 13 Linux/Unix interprocess communication.
Introduction to Socket
Socket Programming Tutorial Department of Computer Science Southern Illinois University Edwardsville Fall, 2015 Dr. Hiroshi Fujinoki
Socket Programming Lab 1 1CS Computer Networks.
Operating Systems Yasir Kiani. 13-Sep Agenda for Today Review of previous lecture Interprocess communication (IPC) and process synchronization UNIX/Linux.
Interprocess Communication Anonymous Pipes Named Pipes (FIFOs) popen() / pclose()
1 제 12 장 프로세스 사이의 통신. 2 Objectives describe how pipes are used for IPC define the two kinds of pipes use the system calls used with pipes network programming.
CSCI 330 UNIX and Network Programming Unit XV: Transmission Control Protocol.
Pipes Pipes are an inter-process communication mechanism that allow two or more processes to send information to each other.
Interprocess Communication
CSE 466 – Fall Introduction - 1 User / Kernel Space Physical Memory mem mapped I/O kernel code user pages user code GPLR virtual kernel C
Named Pipes. Kinds of IPC u Mutexes/Conditional Variables/Semaphores u Pipes u Named pipes u Signals u Shared memory u Messages u Sockets.
Intro to Socket Programming CS 360. Page 2 CS 360, WSU Vancouver Two views: Server vs. Client Servers LISTEN for a connection and respond when one is.
S OCKET P ROGRAMMING IN C Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha.
回到第一頁 Client/sever model n Client asks (request) – server provides (response) n Typically: single server - multiple clients n The server does not need.
In unistd.h : int gethostname(char * name, int maxlen) Purpose : Find the computer's name.
Socket Programming. Computer Science, FSU2 Interprocess Communication Within a single system – Pipes, FIFOs – Message Queues – Semaphores, Shared Memory.
UNIX Sockets Outline UNIX sockets CS 640.
Inter-Process Communication 9.1 Unix Sockets You may regard a socket as being a communication endpoint. –For two processes to communicate, both must create.
1 Spring Semester 2008, Dept. of Computer Science, Technion Internet Networking recitation #7 Socket Programming.
Client-Server model. Socket programming 
Socket Abstraction and Interprocess Communication
Assignment 3 A Client/Server Application: Chatroom
Socket Programming in C
CS 3733 Operating Systems Topics: IPC and Unix Special Files
Transport layer API: Socket Programming
Recitation 11 – 4/29/01 Outline Sockets Interface
Pipes A pipe provides a one-way flow of data example: who | sort| lpr
Socket Abstraction and Interprocess Communication
TCP Sockets Programming
Chapter 12 Interprocess Communication
Network Programming: Part II CSCI 380: Operating Systems Lecture #13
Socket Abstraction and Interprocess Communication
IPC Prof. Ikjun Yeom TA – Hoyoun
Socket Abstraction and Interprocess Communication
Socket Abstraction and Interprocess Communication
Socket Abstraction and Interprocess Communication
Network Programming: Part II CSCI 380: Operating Systems
Socket Abstraction and Interprocess Communication
Internet Networking recitation #8
in unistd.h: int gethostname(char * name, int maxlen)
Sockets.
Presentation transcript:

제12장 프로세스 사이의 통신

목표 describe how pipes are used for IPC define the two kinds of pipes network programming with socket

IPC using Pipes IPC using regular files IPC using pipes unrelated processes can share fixed size life-time lack of synchronization IPC using pipes for transmitting data between related processes can transmit an unlimited amount of data automatic synchronization on open()

Pipes In a UNIX shell, In a shell, UNIX pipes look like: the pipe symbol | (the vertical bar) In a shell, UNIX pipes look like: $ ls -alg | more $ command 1 | command 2 the standard output of command 1 becomes the standard input of command2 We can have longer pipes: $ pic paper.ms | tbl | eqn | ditroff -ms © 숙대 창병모

IPC using Pipes Data transmitting Types of pipes data is written into pipes using the write( ) system call data is read from a pipe using the read( ) system call automatic blocking when full or empty Types of pipes (unnamed) pipes named pipes © 숙대 창병모

Example % who | sort

Pipes #include <unistd.h> int pipe(int fd[2]) Returns: 0 if OK, -1 on error two file descriptors fd[0] : read file descriptor for the pipe fd[1] : write file descriptor for the pipe Anything that is written on fd[1] may be read by fd[0] This is of no use in a single process. A method of communication between processes. A way to communicate with parent-child processes. © 숙대 창병모

Pipe fd[0] fd[1] 프로세스 파이프 커널 © 숙대 창병모

Pipe after fork() 부모 프로세스 파이프 커널 자식 프로세스 fd[0] fd[1] fd[0] fd[1] © 숙대 창병모

Typical use 1) a process creates a pipe 2) fork child process 3) the writer closes its read pipe descriptor, and the reader closes its write pipe descriptor 4) transmitting data via pipe using write() and read() 5) each process closes its active pipe descriptor

부모 프로세스  자식 프로세스 parent  child: parent closes fd[0] fd[0] fd[1] 부모 프로세스 parent  child: parent closes fd[0] child closes fd[1] 파이프 커널 fd[0] fd[1] 자식 프로세스 © 숙대 창병모

자식 프로세스  부모 프로세스 parent  child: parent closes fd[1] fd[0] fd[1] 부모 프로세스 parent  child: parent closes fd[1] child closes fd[0] 파이프 커널 fd[0] fd[1] 자식 프로세스 © 숙대 창병모

Pipes Read from a pipe with write end closed returns 0 to indicate EOF Write to a pipe with read end closed SIGPIPE generated, write() returns error (errno == EPIPE) Atomic write A write of PIPE_BUF (kernel’s pipe buffer size) bytes or less will not be interleaved with the writes from other processes © 숙대 창병모

Sending messages from parent to child #include <unistd.h> /* pipe1.c */ #define MAXLINE 100 int main(void) { int n, fd[2]; int pid; char line[MAXLINE]; if (pipe(fd) < 0) perror("pipe error"); if ( (pid = fork()) < 0) perror("fork error"); else if (pid > 0) { /* parent */ close(fd[0]); write(fd[1], "hello world\n", 12); } else { /* child */ close(fd[1]); n = read(fd[0], line, MAXLINE); write(STDOUT_FILENO, line, n); } exit(0); © 숙대 창병모

FIFO(Name Pipe)

FIFOs Pipes can be used only between related processes FIFOs are "named pipes" can be used between unrelated processes A type of file stat.st_mode == FIFO Test with S_ISFIFO macro © 숙대 창병모

Named pipes Why named pipes ? How to create named pipes ? they have a name that exists in the file system they may be used by unrelated processes they exist until explicitly deleted How to create named pipes ? by using the UNIX mknod commond with the p option $mknod myPipe p $chmod ug+rw myPipe $ls -lg myPipe

FIFOs #include <sys/types.h> #include <sys/stat.h> int mkfifo(const char *pathname, mode_t mode); Returns: 0 if OK, -1 on error Creating FIFOs is similar to creating a file pathname : filename mode: permissons, same as for open() function Using a FIFO is similar to using a file we can open, close, read, write, unlink, etc., to the FIFO © 숙대 창병모

How to communicate via pipes ? Writer process should open a named pipe for write-only write data using write() system call Reader process should open a named pipe for read-only read data using read() system call

Example:Reader #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> main( ) { int fd; char str[100]; unlink(“myPipe”); mkfifo(“myPipe”, 0660); fd = open(“myPipe”, O_RDONLY); while (readLine(fd, str)) printf(“%s\n”, str); close(fd) }

Example:Reader readLine(int fd, char *str; { int n; do { n = read(fd, str, 1); } while (n>0 && *str++ != NULL); return (n>0); }

Example:Writer #include <sys/types.h> #include <sys/stat.h> #include <fcnlt.h> main( ) { int fd, messageLen, i; char message[100]; sprintf(message, “Hello from PID %d”, getpid()); messageLen= strlen(message)+1; do { fd = open(“myPipe”, O_WRONLY); if (fd == -1) sleep(1); } while(fd == -1); for (i =1; i<= 3; i++) { write(fd, message, messageLen); sleep(3); } close(fd);

Socket

Sockets Socket AF_UNIX socket AF_INET socket bidirectional connection process communication based on client-server model AF_UNIX socket an interprocess communication mechanism between processes on the same UNIX machine AF_INET socket an interprocess communication mechanism between processes across network

Socket connection Server Client 1. Sever creates a named socket 2. Client creates an unnamed socket and request a connection 3. Server accepts a connection. Server retains original named socket

Client-Server Model Server Client Server creates a named socket using socket() Server makes a peding queue using listen() Server accept() from a client connection() When a socket isconnected the server usually fork() a child process to converse with the client Client Client creates an unnamed socket using socket() Client requests a connection using connect() Client makes a connection when server accept( ) it.

클라이언트 서버 socket socket bind listen 연결 요청 connect accept EOF close 서비스 요청 서비스 요청 처리 다음 클라이언트로부터 연결 요청을 기다림 응답 처리 서비스 응답 EOF close close

Creating a Socket Example 소켓 만들기 int socket(int domain, int type, int protocol) domain AF_UNIX AF_INET type SOCK_STREAM protocol DEFAULT _PROTOCOL Example fd = socket(AF_UNIX, SOCK_STREAM, DEFAULT_PROTOCOL);

Naming a Socket 소켓에 이름(주소) 주기 int bind(int fd, struct sockaddr* address, int addressLen) bind the unnamed socket with fd to a name in address address is a pointer to struct sockaddr_un sun_family = AF_UNIX sun_path = name of the socket struct sockaddr_in sin_family = AF_INET sin_port = the port number of Internet socket sin_addr = 32-bit IP address sin_zero = leave empty addressLen = length of address structure

Example serverUNIXAddress.sun_family = AF_UNIX; strcpy(serverUNIXAddress.sun_path, “convert”); unlink(“convert”); bind(fd, &serverUNIXAddress, serverLen);

Creating a Socket Queue 소켓 큐 생성 int listen(int fd, int queueLength) specify the maximum number of pending connections on a socket example listen(serverFd, 5);

Making the Connection 소켓에 연결 요청 int connect(int fd, struct sockaddr* address, int addressLen) attempts to connect to a server socket whose address is in a structure pointed to by address If successful, fd may be used to communicate with the server’s socket

(1) listen to the named server socket referenced by fd Accepting a Client 소켓 연결 요청 수락 int accept(int fd, struct sockaddr* address, int* addressLen) (1) listen to the named server socket referenced by fd (2) wait until a client connection request is received (3) creates an unnamed socket with the same attributes as the original server socket, and connects it to the client’s socket. (4) When a connection is made, address is set to the address of the client socket and addressLen is set to the actual size (5) return a new file descriptor

Convert Server/Client 이 프로그램은 입력 받은 문자열을 소문자를 대문자로 변환한다. 서버 소켓을 통해 클라이언트로부터 받은 문자열을 소문자를 대문자로 변환하여 소켓을 통해 클라이언트에 다시 보낸다.  클라이언트 표준입력으로부터 문자열을 입력 받아 이를 소켓을 통해 서버에 보낸 후에  소켓을 통해 대문자로 변환된 문자열을 다시 받아 표준출력에 출력한다.

Convert Server(1/3) #include <stdio.h> #include <signal.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #define DEFAULT_PROTOCOL 0 #define MAXLINE 100 main ( ) { int listenfd, connfd, clientlen; char inmsg[MAXLINE], outmsg[MAXLINE]; struct sockaddr_un serverUNIXaddr, clientUNIXaddr; signal(SIGCHLD, SIG_IGN); clientlen = sizeof(clientUNIXaddr); listenfd = socket(AF_UNIX, SOCK_STREAM, DEFAULT_PROTOCOL); serverUNIXaddr.sun_family = AF_UNIX; strcpy(serverUNIXaddr.sun_path, "convert");

Convert Server(2/3) unlink("convert"); bind(listenfd, &serverUNIXaddr, sizeof(serverUNIXaddr)); listen(listenfd, 5); while (1) { connfd = accept(listenfd, &clientUNIXaddr, &clientlen); if (fork ( ) == 0) { readLine(connfd, inmsg); toUpper(inmsg, outmsg); write(connfd, outmsg, strlen(outmsg)+1); close(connfd); exit (0); } else close(connfd); }

Convert Server(3/3) toUpper(char* in, char* out) { int i; for (i = 0; i < strlen(in); i++) if (islower(in[i])) out[i] = toupper(in[i]); else out[i] = in[i]; out[i] = NULL; }

Convert Client(1/2) #include <stdio.h> #include <signal.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #define DEFAULT_PROTOCOL 0 #define MAXLINE 100 main ( ) { int clientfd, serverLen, result; char inmsg[MAXLINE], outmsg[MAXLINE]; struct sockaddr_un serverUNIXaddr; clientfd = socket(AF_UNIX, SOCK_STREAM, DEFAULT_PROTOCOL); serverUNIXaddr.sun_family = AF_UNIX; strcpy(serverUNIXaddr.sun_path, "convert");

Convert Client(2/2) do { result = connect(clientfd, &serverUNIXaddr, sizeof(serverUNIXaddr)); if (result == -1) sleep(1); } while (result == -1); fgets(inmsg, MAXLINE, stdin); write(clientfd,inmsg,strlen(inmsg)+1); readLine(clientfd,outmsg); printf("%s --> \n%s", inmsg, outmsg); close(clientfd); exit(0); } 39