Chinaunix首页 | 论坛 | 博客
  • 博客访问: 399694
  • 博文数量: 83
  • 博客积分: 2011
  • 博客等级: 大尉
  • 技术积分: 741
  • 用 户 组: 普通用户
  • 注册时间: 2009-04-04 22:51
文章分类

全部博文(83)

文章存档

2009年(83)

我的朋友

分类: LINUX

2009-07-27 20:59:49

管道只能单向传输数据.只能用于父子或兄弟进程间的.
管道单独构成一种独立的文件系统.
 
表头文件 #include
定义函数 int pipe(int pipe_fd[2]);
函数说明
    pipe()会建立管道,并将文件描述词由参数 filedes 数组返回。
    pipe_fd[0]为管道里的读取端. pipe_fd[0]用来从管道中读取数据.
    pipe_fd[1]则为管道的写入端。pipe_fd[1]用来把数据写入管道.
 
用write()把数据从管道写入pipe_fd[1] ,   read()从pipe_fd[0] 中读取数据到管道.
返回值:  若成功则返回零,否则返回-1,错误原因存于 errno 中。
错误代码:
    EMFILE 进程已用完文件描述词最大量
    ENFILE 系统已无文件描述词可用。
    EFAULT 参数 filedes 数组地址不合法。
 
以下为一个例子:
#include
#include
#include
#include
#include
#include
int main()
{
 pid_t result;
 int r_num;
 int pipe_fd[2];
 char buf_r[100];
 memset(buf_r, 0, sizeof(buf_r));
 if (pipe(pipe_fd) < 0)
 {
  perror("creat pipe failed");
  return -1;
 }
 
 result = fork();
 if (result < 0)
 {
  perror("creat child failed");
  exit(1);
 }
 else if (result == 0)
 {
  close(pipe_fd[1]);
  if ((r_num = read(pipe_fd[0], buf_r, 100)) > 0)
  {
   printf("child process read %d word from pipe, the string is %s\n", \
     r_num, buf_r);
  }
  close(pipe_fd[0]);
  exit(0);
 }
 else
 {
  close(pipe_fd[0]);
  if (write(pipe_fd[1], "the first string", 17) != -1)
  {
   printf("parent write first string into pipe!\n");
  }
  if (write(pipe_fd[1], "the second string", 18) != -1)
  {
   printf("parent write second string into pipe!\n");
  }
  close(pipe_fd[1]);
  waitpid(result, NULL, 0);
  exit(0);
 }
}
 
 
 
阅读(1590) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~