zoukankan      html  css  js  c++  java
  • 管道

     

     1 #include <stdio.h>
     2 #include <string.h>
     3 #include <sys/types.h>
     4 #include <sys/wait.h>
     5 #include <unistd.h>
     6 
     7 void client(int, int), server(int, int);
     8 
     9 int main(int argc, char **argv)
    10 {
    11     int        pipe1[2], pipe2[2];
    12     pid_t    childpid;
    13     pipe(pipe1);
    14     pipe(pipe2);
    15     if ( (childpid = fork()) == 0) {
    16         close(pipe1[1]); 
    17         close(pipe2[0]); 
    18         server(pipe1[0], pipe2[1]); 
    19         exit(0);
    20     }
    21         
    22     close(pipe1[0]); 
    23     close(pipe2[1]); 
    24     client(pipe2[0], pipe1[1]); 
    25     waitpid(childpid, NULL, 0);    
    26     
    27     exit(0);
    28 }
    mainpipe.c
     1 #include <stdio.h>
     2 #include <string.h>
     3 #include <unistd.h>
     4 
     5 #define MAXLINE 1024
     6 
     7 void client(int readfd, int writefd)
     8 {
     9     size_t    len;
    10     ssize_t    n;
    11     char    buff[MAXLINE];
    12     
    13     while(NULL != fgets(buff, MAXLINE, stdin))
    14     {            
    15         len = strlen(buff);    
    16         if (buff[len-1] == '
    ')
    17             len--;        
    18             
    19         write(writefd, buff, len); 
    20         
    21         if(0 != read(readfd, buff, MAXLINE))
    22         {
    23             fputs(buff, stdout);
    24         }
    25     }
    26 }
    client.c
     1 #include <stdio.h>
     2 #include <string.h>
     3 #include <unistd.h>
     4 
     5 #define MAXLINE 1024
     6 
     7 void server(int readfd, int writefd)
     8 {
     9     ssize_t    n;
    10     char    buff[MAXLINE+1];
    11     
    12     while(1)
    13     {
    14         if ( (n = read(readfd, buff, MAXLINE)) == 0)
    15         {
    16             printf("end-of-file while reading pathname");
    17             return;
    18         }
    19         buff[n] = '';        
    20             
    21         write(writefd, buff, n); 
    22 
    23         sleep(1);
    24     }
    25 }
    server.c
  • 相关阅读:
    数据库之ORACLE常见基础操作
    数据库基础之Oracle函数
    Snuketoon [ABC217H]
    Cards [CF1278F]
    Squirrel Migration [ARC087F]
    Xor Query [ABC223H]
    Three Permutations [ABC214G]
    雨林跳跃[APIO2021]
    Redis5.0 主从模式和高可用 搭建和测试报告
    Redis5 压力测试结果反馈报告
  • 原文地址:https://www.cnblogs.com/paullam/p/3615233.html
Copyright © 2011-2022 走看看