1. This is pipe2.c. It start rather like the first examples, up until we make the call to fork.
UNIX allows two ways of opening a pipe:

popen() -- Formatted Piping

FILE *popen(char *command, char *type) -- opens a pipe for I/O where the command is the process that will be connected to the calling process thus creating the pipe. The type is either ``r'' - for reading, or ``w'' for writing.

popen() returns is a stream pointer or NULL for any errors.

A pipe opened by popen() should always be closed by pclose(FILE *stream).

We use fprintf() and fscanf() to communicate with the pipe's stream.

 

pipe() -- Low level Piping

int pipe(int fd[2]) -- creates a pipe and returns two file descriptors, fd[0], fd[1]. fd[0] is opened for reading, fd[1] for writing.

pipe() returns 0 on success, -1 on failure and sets errno accordingly.

The standard programming model is that after the pipe has been set up, two (or more) cooperative processes will be created by a fork and data will be passed using read() and write().

Pipes opened with pipe() should be closed with close(int fd).

 

Try It Out - Pipes across a fork

1. This is pipe2.c. It start rather like the first examples, up until we make the call to fork.

2. We've made sure the fork worked, so if fork_result equals zero, we're in the child process:

3. Otherwise, we must be the parent process:

 

文章標籤
全站熱搜
創作者介紹
創作者 phchiu 的頭像
phchiu

日常瑣碎事

phchiu 發表在 痞客邦 留言(0) 人氣(53)