Chapter 7. Pipe 2 pipe 개요  Simple IPC (inter process communication) mechanism  두 프로세스간 통신 기능 제공  동작 방식  수도관 (pipe) 을.

Slides:



Advertisements
Similar presentations
Unix IPC and Synchronization. Pipes and FIFOs Pipe: a circular buffer of fixed size written by one process and read by another int pipe(int fildes[2])
Advertisements

4.1 Operating Systems Lecture 11 UNIX Pipes Read Handout "An Introduction to Concurrency..."
Operating Systems Yasir Kiani. 20-Sep Agenda for Today Review of previous lecture Use of FIFOs in a program Example code Process management commands.
System-Level I/O Topics Unix I/O Robust reading and writing Reading file metadata Sharing files I/O redirection Standard I/O.
1 Processes Professor Jennifer Rexford
1 Processes and Pipes COS 217 Professor Jennifer Rexford.
CS 311 – Lecture 09 Outline Introduction to Systems programming – System calls – Categories of system calls Error Management System calls File Handling.
1 Processes and Pipes. 2 "He was below me. I saw his markings, manoeuvred myself behind him and shot him down. If I had known it was Saint-Exupery, I.
Rings This chapter demonstrates how processes can be formed into a ring using pipes for communication purposes.
Exec function Exec function: - replaces the current process (its code, data, stack & heap segments) with a new program - the new program starts executing.
Today’s topic Inter-process communication with pipes.
Operating systems Lab 04 System Call, Nested Fork(),Exec(),Pipe()
Unix Processes Slides are based upon IBM technical library, Speaking Unix, Part 8: Unix processes Extended System Programming Laboratory (ESPL) CS Department.
1 UNIX Systems Programming Interprocess communication.
Shell (Part 1). Process r A process is an instance of an application running r If there are two instances of an application running then there are two.
Agenda  Terminal Handling in Unix File Descriptors Opening/Assigning & Closing Sockets Types of Sockets – Internal(Local) vs. Network(Internet) Programming.
Unix Pipes Pipe sets up communication channel between two (related) processes. 37 Two processes connected by a pipe.
1 Homework Introduction to HW7 –Complexity similar to HW6 –Don’t wait until last minute to start on it File Access will be needed in HW8.
Slide 1 Interprocess communication. Slide 2 1. Pipes  A form of interprocess communication Between processes that have a common ancestor  Typical use:
1 System-Level I/O Andrew Case Slides adapted from Jinyang Li, Randy Bryant and Dave O’Hallaron.
OPERATING SYSTEMS 12 - FILES PIETER HARTEL 1. Files  Properties  Long term existence of data  Sharable between processes  Access control  Operations.
Cli/Serv.: procs/51 Client/Server Distributed Systems v Objectives –look at how to program UNIX processes , Semester 1, Processes.
1 Week 2 The Crunchy Shell to the Soft and Chewy Kernel… Sarah Diesburg 8/3/2010 COP4610 / CGS5765.
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.
CS162B: Pipes Jacob T. Chan. Pipes  These allow output of one process to be the input of another process  One of the oldest and most basic forms of.
Agenda  Redirection: Purpose Redirection Facts How to redirecting stdin, stdout, stderr in a program  Pipes: Using Pipes Named Pipes.
Chapter 71 Deadlock Detection revisited. Chapter 72 Message Passing (see Section 4.5 in Processes Chapter)  A general method used for interprocess communication.
Shell (Addendum). 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.
S -1 Pipes. S -2 Inter-Process Communication (IPC) Chapter Data exchange techniques between processes: –message passing: files, pipes, sockets.
Chapter 11 Process Management
Pipe-Related System Calls COS 431 University of Maine.
Operating Systems Lecture 10. Agenda for Today Review of previous lecture Input, output, and error redirection in UNIX/Linux FIFOs in UNIX/Linux Use of.
1 IT 252 Computer Organization and Architecture Interaction Between Systems: File Sharing R. Helps.
Operating Systems Process Creation
1 Tutorial: CSI 3310 Dewan Tanvir Ahmed SITE, UofO.
File descriptor table File descriptor (integer)File name 0stdin 1stdout 2stderr Use open(), read(), write() system calls to access files Think what happens.
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 XII: Process & Pipe Part 1.
Recitation 11 (Nov. 22) Outline Lab 6: interposition test Error handling I/O practice problem Reminders Lab 6: Due Tuesday Minglong Shao
Laface 2007 File system 2.1 Operating System Design Filesystem system calls buffer allocation algorithms getblk brelse bread breada bwrite iget iput bmap.
Pipes Pipes are an inter-process communication mechanism that allow two or more processes to send information to each other.
Interprocess Communication
제12장 프로세스 사이의 통신.
Dsh: A Devil Shell COMPSCI210 Recitation 14 Sep 2012 Vamsi Thummala.
[Unix Programming] Interprocess Communication - PIPE Young-Ju, Han
Dup, dup2 An existing file descriptor ( filedes ) is duplicated The new file descriptor returned by dup is guaranteed to be the lowest numered available.
Using System Calls (Unix) Have to tell compiler (if C/C++) where to find the headers, etc. – i.e., the “include” files May have to tell compiler where.
Copyright ©: Nahrstedt, Angrave, Abdelzaher, Caccamo1 Pipes and Fifos.
1 Intro to the Shell with Fork, Exec, Wait Sarah Diesburg Operating Systems CS 3430.
Files in UNIX u UNIX deals with two different classes of files:  Special Files  Regular Files u Regular files are just ordinary data files on disk -
Lecture 5 Systems Programming: Unix Processes: Orphans and Zombies
Week 3 Redirection, Pipes, and Background
CS 3305A Process – Part II Lecture 4 Sept 20, 2017.
Introduction to Operating Systems File I/O
CS 3733 Operating Systems Topics: IPC and Unix Special Files
Operating Systems Lecture 11.
Pipe.
Pipes A pipe provides a one-way flow of data example: who | sort| lpr
LINUX System Programming with Processes (additional)
תרגול 8 – ק/פ ותקשורת תהליכים ב-Linux
Programming Assignment # 2 – Supplementary Discussion
IPC Prof. Ikjun Yeom TA – Hoyoun
dup, dup2 An existing file descriptor (filedes) is duplicated
Intro to the Shell with Fork, Exec, Wait
System Programming: Process Management
Presentation transcript:

Chapter 7. Pipe

2 pipe 개요  Simple IPC (inter process communication) mechanism  두 프로세스간 통신 기능 제공  동작 방식  수도관 (pipe) 을 통해서 흐르는 물 ( 데이터 ) 과 유사  Writing process 와 Reading process 사이에 동기화를 제공  Writing process 가 아직 write 를 하지 않은 파이프에서 read 하는 경우  read(2) 가 block  Reading process 가 읽지 않고, writing process 가 계속 write 하여 파이프가 가득 찬 경우  write(2) 가 block

3 pipe(2) #include int pipe (int filedes[2]);  pipe 의 생성  수행결과  filedes[0]  파이프에서 읽기 위한 file descriptor 값이 저장됨  filedes[1]  파이프에 쓰기를 위한 file descriptor 값이 저장됨  Return  Success : 0  Failure : -1 and erron is set

4 pipe(2): 수행 결과

5 pipe(2) 적용 가능한 시스템 호출들  open(2)  사용 안됨  close(2)  파이프로의 접근이 완료되었을 때 사용  read(2)  파이프가 비어있다면 멈춤 (block)  write(2)  파이프가 꽉 차있다면 멈춤 (block)  lseek(2)  사용 안됨  dup(2)  파이프로의 입출력 방향을 변경 (redirection) 을 위해 사용됨  fcntl(2)  입출력시 지연이 없도록 함

6 pipe(2): Examples

7 #include #define MSGSIZE 20 main (int argc, char *argv[]) { int fd[2], pid; char msgin[MSGSIZE], msgout[MSGSIZE] = "\nHello, world\n"; if (pipe(fd) == -1) { perror(argv[0]); exit(1); } if ((pid = fork()) > 0) {/* parent */ write (fd[1], msgout, MSGSIZE); } else if (pid == 0) {/* child */ read (fd[0], msgin, MSGSIZE); puts (msgin); }

8 % gcc q.c % a.out % Hello, world %

9 who.c: 전체 동작

10 who.c #include char text[80]; main (int argc, char **argv) { int fd[2]; if (pipe(fd) == -1) { perror(argv[0]); exit(1); } if (fork() == 0) {/* first child */ close (1); dup (fd[1]);/* redirect std output */ close (fd[0]); close (fd[1]); printf ("who display sorted\n"); fflush (stdout); execl ("/usr/bin/who", "who", (char*) 0); exit (127); }

11 who.c: 현재 상태

12 who.c: 계속 if (fork() == 0) {/* second child */ close (0); dup (fd[0]);/* redirect std input */ close (fd[0]); close (fd[1]); read2line (text); printf ("\tHeading: %s\n", text); fflush (stdout); /* sort 는 stdin 입력, stdout 출력 */ execl ("/bin/sort", "sort", (char*) 0); exit (127); } close (fd[0]); close (fd[1]); while (wait((char*)0) != -1) ; exit(0); } read2line(char *input) { while (1) { read (0, input, 1); if (*input == '\n') break; else input++; }

13 % a.out Heading: who display sorted dksungpts/55 월 17 09:03( ) egkimpts/95 월 18 17:27( ) rootconsole4 월 7 11:23(:0) rootpts/34 월 7 11:23(:0.0) rootpts/85 월 17 10:43(:0.0) %

14 create_pipe1.c: 전체 동작

15 % a.out this is test... [Parent] : Send Message : this is test... [Child] : Receive Message : this is test... [Child] : Send Message : this is test... [Parent] : Receive Message : this is test... %

16 create_pipe1.c: 학생들이 직접 읽고 해석. #include #define MAX_SIZE 50 main() { int send_fd[2], rcv_fd[2], pid=0, size=0; char send_buf[MAX_SIZE], rcv_buf[MAX_SIZE]; memset (send_buf, 0x00, MAX_SIZE); memset (rcv_buf, 0x00, MAX_SIZE); if ( pipe(send_fd) == -1 ) { perror("pipe() : "); exit(1); } if ( pipe(rcv_fd) == -1 ) { perror("pipe() : "); exit(2); }

17 if ((pid = fork()) == 0 ) {/* Child */ close(send_fd[1]); close(rcv_fd[0]); size = read(send_fd[0], rcv_buf, MAX_SIZE); printf("\t[Child] : Receive Message : %s\n", rcv_buf); write(rcv_fd[1], rcv_buf, size); printf("\t[Child] : Send Message : %s\n", rcv_buf); exit(0); } else if ( pid > 0 ) {/* Parent */ close(send_fd[0]); close(rcv_fd[1]); size = read(0, send_buf, MAX_SIZE); write(send_fd[1], send_buf, size); printf("[Parent] : Send Message : %s\n", send_buf); read(rcv_fd[0], rcv_buf, MAX_SIZE); printf("[Parent] : Receive Message : %s\n", rcv_buf); }

18 create_pipe2.c: 전체 동작

19 create_pipe2.c #include #define MAX_SIZE 50 main (int argc, char *argv[]) {int fd[2], pid=0, size=0, status=0; char buf[MAX_SIZE]; memset (buf, 0x00, MAX_SIZE); if ( pipe(fd) == -1 ) { perror("pipe() : ");exit(1); } if ( fork() == 0 ) { close(0); dup(fd[0]); close(fd[0]); close(fd[1]); size = read(0, buf, MAX_SIZE); execlp(buf, buf, (char *)NULL); perror("execlp() : ");exit(3); }

20 if ( fork() == 0 ) { close (1);dup (fd[1]); close (fd[0]);close (fd[1]); printf ("%s", argv[1]); fflush (stdout); exit(0); } close (fd[0]);close(fd[1]); while ( wait(&status) != -1 ) ; exit(0); }

21 % a.out date ( 수 ) 11:28:16 KST %

22 실습  7 page  10 ~ 12 page  16 ~ 17 page  학생들이 직접 읽고 해석한 이후에 실습  유사한 시험 문제 나올 수 있음.  19 ~ 20 page

23 Pipe 표준 라이브러리  생략

24 mknod(1)  Create a special file  Block special file  /dev/hda: hard-disk b brw-rw root disk 3, 0 Mar /dev/hda  Character special file  /dev/tty c crw-rw-rw- 1 root root 5, 0 Mar /dev/tty  FIFO  Named pipe 를 위한 파일 p prw-rw-r-- 1 egkim egkim 0 Mar 19 19:17 pipeFile  Named pipe 를 위한 special file 의 생성 % mknod pipeFile p %

25 mknod(1) 의 사용 예 : Shell % cat data 1 abcdefghijklmnopqrstuvwxyz 2 abcdefghijklmnopqrstuvwxyz 3 abcdefghijklmnopqrstuvwxyz % % ls data % mknod NP p % ls NPdata % cat NP blocking until data received 1 abcdefghijklmnopqrstuvwxyz 2 abcdefghijklmnopqrstuvwxyz 3 abcdefghijklmnopqrstuvwxyz % % cat data > NP send data to NP %

26 mknod(3): #include int mknod (const char *pathname, mode_t mode, dev_t dev);  Create a directory or special or ordinary file  Parameter  pathname: 경로를 포함하는 파일 이름  mode: 생성하려는 파일의 permission 및 type (“|” 로 조합 )  Type  S_IFREGS_IFCHRS_IFBLK S_IFIFO  S_IFREG ( 일반 파일 ), S_IFCHR (character special file), S_IFBLK (block special file), S_IFIFO (named pipe)  예 : mknod (“pipeFile ”, S_IFIFO | 0660, 0);  dev: FIFO 용 으로는 사용하지 않음  Return  Success : 0  Failure : -1 and errno is set

27 Named pipe 에 적용 가능한 시스템 호출들  open(2)  정규 파일에서와 동일하게 사용  clos(2)  Named pipe 로의 접근이 완료되었을 때 사용  read(2)  일반적으로 데이터가 없으면 멈춤 (block)  write(2)  일반적으로 파이프에 데이터가 꽉 차면 멈춤 (block)  lseek(2)  사용하지 않음  dup(2)  파이프로 입출력 방향을 변경 (redirection) 을 위해 사용됨  fcntl(2)  입출력을 위한 지연이 없도록 set 할 때 사용

28 Named Pipe Example: Client-Server mode

29 Client – Server Program  namedPipe.h struct message { char privfifo[15]; /* name of private named pipe */ char filename[100]; /* name of file */ }; #define PUBLIC "Public" #define LINESIZE 512 #define NUMTRIES 3

30 file_server.c #include #include "namedPipe.h" main (int argc, char *argv[]) { int fdpub, fdpriv, fd, n, i; struct message msg; char line[LINESIZE]; /* mknod(1) 을 이용하여, FIFO special file 을 만들지 않았으면 생성 */ /* 이미 만들어져 있으면, mknod(2) 에러 발생 무시 */ mknod (PUBLIC, S_IFIFO|0666, 0); if ((fdpub = open(PUBLIC, O_RDONLY)) == -1) { perror(PUBLIC);exit(1); }

31 loop: /* forever */ while (read(fdpub, (char *) &msg, sizeof(msg)) >0) { printf (“Client Request Arrived.\n”); if ((fd=open(msg.filename, O_RDONLY)) == -1) { perror(msg.filename);break; } for (i= 0; i< NUMTRIES; i++) if ((fdpriv = open(msg.privfifo, O_WRONLY|O_NDELAY)) == -1) sleep(1); elsebreak; if (fdpriv == -1) { perror (msg.privfifo);break; } while ((n=read(fd, line, LINESIZE)) > 0) write (fdpriv, line, n); close (fd);close (fdpriv); } goto loop; }

32 client.c #include #include "namedPipe.h" main (int argc, char *argv[]) { struct message msg; int n, fdpub, fdpriv; char line[LINESIZE]; sprintf (msg.privfifo, "Fifo%d", getpid()); if (mknod(msg.privfifo, S_IFIFO| 0666, 0) == -1) { perror(msg.privfifo); exit(1); }

33 if ((fdpub = open(PUBLIC, O_WRONLY)) == -1) { perror (PUBLIC);exit(2); } strcpy (msg.filename, argv[1]); write (fdpub, (char *) &msg, sizeof(msg)); if ((fdpriv = open(msg.privfifo, O_RDONLY)) ==-1) { perror (msg.privfifo);exit(3); } while ((n=read(fdpriv, line, LINESIZE)) > 0) write(1,line,n); close (fdpriv); unlink (msg.privfifo); exit(0); }

34 % gcc -o server server.c % gcc -o client client.c % % server Client Request Arrived. % cat data 1 abcdefghijklmnopqrstuvwxyz 2 abcdefghijklmnopqrstuvwxyz 3 abcdefghijklmnopqrstuvwxyz % % client data 1 abcdefghijklmnopqrstuvwxyz 2 abcdefghijklmnopqrstuvwxyz 3 abcdefghijklmnopqrstuvwxyz %