文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>管道函数.

管道函数.

时间:2009-07-27  来源:tancotq

管道只能单向传输数据.只能用于父子或兄弟进程间的. 管道单独构成一种独立的文件系统.   表头文件 #include<unistd.h>
定义函数 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 <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <string.h>
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);
 }
}
     
相关阅读 更多 +
排行榜 更多 +
立体反应点击

立体反应点击

休闲益智 下载
料理物语

料理物语

休闲益智 下载
滑杆优雅舞者

滑杆优雅舞者

休闲益智 下载