unix/linux编程实践教程----I/O重定向和管道

来源:互联网 发布:c语言rinv 编辑:程序博客网 时间:2024/06/11 05:47

(1)概念:

I/O重定向:指针对一个进程,将其输入或者输出从标准I/O换成文件。

     管道    :进程间通信。

(2)I/O重定向:

最低可用文件描述符原则:文件描述符的概念很简单,就是数组的索引。每个进程都有一系列与之相关联的文件,这些打开的文件保存在一个数组之中,文件描述符就是这个数组的下标。当打开文件时,为此文件安排的总是此数组中最低可用位置。

            将stdin定向到文件:2种方法:

(1)close(0),open(file)

(2)fd=open(file),close(0),newfd=dup(fd),close(fd);

     将stout定向到文件:类似于上面,但注意要在子进程的处理函数中执行这些。


(3)管道编程:

(1)管道是内核中一个单向的数据通道,用系统调用pipe进行创建

(2)系统调用:pipe(int file[2])

参数数组的两个成员分别是连接管道的两个文件的文件描述符

     其中file[0]是用来读的,file[1] 是用来写的

使用pipe实现两个进程通信

(3)当进程试图从管道中读取数据时,进程被挂起直到数据被写进管道。


#include<stdio.h>#include<string.h>#define CHILD_MESS "i want a cookie"#define father_MESS "testing...."#define oop(m,x)  {perror(m),exit(x);}main(){  int pipe_1[2],len,read_len;  char buf[BUFSIZ];  if(pipe(pipe_1)==-1)    oop("can not get pipe",1);  switch(fork())    {    case -1: oop("cannot fork",1);    case 0:      {len=strlen(CHILD_MESS);while(1)  {    if(write(pipe_1[1],CHILD_MESS,len)!=len)      oop("write",2);    sleep(5);  }      }    default:      {len=strlen(father_MESS);while(1)  {    if(write(pipe_1[1],father_MESS,len)!=len)      oop("write",2);    sleep(1);    read_len=read(pipe_1[0],buf,BUFSIZ);    write(1,buf,read_len);  }      }    }}


0 0
原创粉丝点击