pipe system call(原创)

使用unix的时候,比如说在C shell上输入[lastmore -10],就会从[more -10]的输入给出[last]的输出结果。unix这样的机能就叫做pipe

 

为了实现pipe,先用pipe system call做出pipe用的file descriptor(文件描述符)。为了解释pipe system call的用法,给出了以下的简单program

 

     1  #include

 

     2

 

     3  #define BSIZE 512

 

     4  char send_buf[]="Computer Science";

 

     5

 

     6  main(){

 

     7    int p_fd[2],n_send,n_recv;

 

     8    char recv_buf[BSIZE];

 

     9   

 

    10    pipe(p_fd);

 

    11   

 

    12    n_send = strlen(send_buf)+1;

 

    13    write(p_fd[1],send_buf,n_send);

 

    14    close(p_fd[1]);

 

    15   

 

    16    n_recv = read(p_fd[0],recv_buf,BSIZE);

 

    17    close(p_fd[0]);

 

    18   

 

    19    printf("%d bytes sent, %d bytes recieved./n",n_send,n_recv);

 

    20    printf("recieved data: %s/n",recv_buf);

 

    21

 

    22    exit(0);

 

    23  }

 

 

pipe system call取一个参数,用这个参数指定由有2个整数型要素的数列。10行把数列p_fd作为参数呼出pipe system callpipe system call成功的话,返回值返回0,在p_fd[0]里存入输入侧的file descriptorp_fd[1]存入输出侧的file descriptor

 

13行的pipe的输出侧输出Computer Science。(15行的strlen函数是求文字列的文字数的库函数。)然后,输出结束的file descriptor p_fd[1]变得不再需要了消除。

 

16行,从pipe的输入侧对recv_buf进行输入。结束之后像上面一样file descriptor p_fd[0]不再需要,消除。

 

最后表示出 pipe输出侧的输出文字数,从pipe输入侧输入的文字数(都是17bit)。然后表示输入用bufrecv_buf的内容,确定通过pipeComputer Science这个数据正确的传输了。

 

结果如下:

 

$ ./a.out

 

17 bytes sent, 17 bytes recieved.

 

recieved data: Computer Science

 

(以上文章的版权在fastso,转载时请与本人取得联系,谢谢!)

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(Unix/Linux)