Pipe---sample

Pipes
In Unix, a pipe is a unidirectional, stream communication abstraction. Show a picture!! One process writes to the ``write end'' of the pipe, and a second process reads from the ``read end'' of the pipe.

The command interpreter is responsible for setting up a pipe. For instance, upon entering:

% ls | more

the shell would:

create a pipe.

create a process for the ls command, setting stdout to the write side of the pipe.

create a process for the more program, setting stdin to the read side of the pipe.
A pipe consists of (keep using the same picture showing the pipe as a buffer)


two descriptors, one for reading, one for writing.

reading from the pipe advances the read pointer

writing to the pipe advances the write pointer

example of the bounded-buffer problem:

operating system buffers data in the pipe (Unix pipe 4096 bytes (4K))

operating system blocks reads of empty pipe

operating system blocks writes to full pipe

pipe data consists of unstructured character stream
Pipes unify input and output. When a process starts up, it inherits open file descriptors from its parent.


by convention, file descriptor 0 is standard input

file descriptor 1 is standard output

file descriptor 2 is standard error
Thus, when a process reads from standard input, it doesn't know (or care!) whether it is reading from a file or from another process.

Likewise, output written to standard output might go to a terminal, a file, or another process.

System calls:


count = read(fd, buffer, nbytes) reads from a file descriptor, scanf/cin built on top of.

count = write(fd, buffer, nbytes) writes to a file descriptor, printf/cout built on top of.

error = pipe(rgfd) creates a pipe. rgfd is an array of two file descriptors. Read from rgfd[0], write to rgfd[1].
CODE


/* pipe.C */

#include <iostream.h>
#include <unistd.h>

#define DATA "hello world"
#define BUFFSIZE 1024

int rgfd[2];    /* file descriptors of streams */

/* NO ERROR CHECKING, ILLUSTRATION ONLY!!!!! */

main()
{
   char sbBuf[BUFFSIZE];

   pipe(rgfd);    
   if (fork()) { /* parent, read from pipe */
       close(rgfd[1]);   /* close write end */
       read(rgfd[0], sbBuf, BUFFSIZE);
       cout << "-->" << sbBuf << '\n';
       close(rgfd[0]);
   }
   else { /* child, write data to pipe */
       close(rgfd[0]);   /* close read end */
       write(rgfd[1], DATA, sizeof(DATA));
       close(rgfd[1]);
       exit(0);
   }
}


For the following, which is the parent and which is the child? (parent should read from pipe so ``more'' is the parent process). Last to complete.


% ls | more

作者: 蓝色键盘   发布时间: 2003-10-20

朋友,日子就一天比一天难过了。(二)有风。镖旗飞扬。黑色的大北京白癜风的治疗在哪里。邓定侯抬起头,看看斜插在第一辆车上的大旗,脸上不禁露北京白癜风的治疗竟要我想什么呢?”丁喜道:“每件事你都可以想,想通了之后再去http://sell.b2bvip.com/business/c-1723905.html他?”丁喜没有开口,门外已有个人带着笑道:“他来找的不是我,北京白癜风的治疗”花衣镖客道:“你还看不出?”小马道:“我只看出了你既不是东

作者: dfjaljl   发布时间: 2011-10-26