当前位置:网站首页>Unix System Programming Chapter 15 15.2 Pipes

Unix System Programming Chapter 15 15.2 Pipes

2022-08-09 10:28:00 Mary soda Patty

Pipe is the oldest form of IPC in UNIX systems, and all UNIX systems provide this communication mechanism.

Pipelines have two limitations:

  1. Historically, they were half-duplex (ie data only flowed in one direction).Some systems now offer full-duplex pipes.
  2. Pipes can only be used between two processes with a common ancestor. Usually, a pipe is created by a process. After the process calls fork, the pipe can be used between the parent process and the child process.

We will see that FIFOs do not have the second limitation, and UNIX domain sockets do not have either.

A pipe is created by calling the pipe function.

#include int pipe(int fd[2]);//Return value, return 0 for success, -1 for error

Two file descriptors are returned via the parameter fd: fd[0] is open for reading and fd[1] is open for writing.The output of fd[1] is the input of fd[0].

A pipe for a single process is of little use, usually a process will call pipe followed by fork to create an IPC channel from parent to child and vice versa.

What to do after the fork depends on the direction of data flow we want. For pipes from parent to child, the parent closes the read end of the pipe and the child closes the write end.

The following two rules apply when one end of the pipe is closed.

  1. When reading a pipe whose write end has been closed, after all data has been read, read returns 0, indicating end of file.
  2. If writing to a channel whose read end has been closed, the signal SIGPIPE is generated. If the signal is ignored or caught and returned from its handler, write returns -1 and errno is set to EPIPE.

Sample program:

#include "apue.h"int main(){int n;int fd[2];pid_t pid;char line[MAXLINE];if(pipe(fd)<0)err_sys("pipe error");if((pid=fork())<0)err_sys("fork error");else if(pid>0){close(fd[0]);write(fd[1],"hello world\n",12);}else{close(fd[1]);n=read(fd[0],line,MAXLINE);write(STDOUT_FILENO,line,n);}exit(0);}

原网站

版权声明
本文为[Mary soda Patty]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/221/202208091026200944.html