pipe.txt

来自「linux下管道监视程序」· 文本 代码 · 共 63 行

TXT
63
字号
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

int main()
{
    int fd[2], status;
    int cld1_pid, cld2_pid, cld3_pid;
    static int x1 = 0, x2 = 0, x3 = 0;
    char buf[200], buf1[200], buf2[200], buf3[200], len;
    
    if(pipe(fd) == -1) {
        printf("Create pipe error. \n");
        exit(1);
    }
   
    if((cld1_pid = fork()) == 0) {
        close(fd[0]);
        while(x1 < 3) {
             sleep(1);
             sprintf(buf1, "process 1 send message %d.\n", x1);
             write(fd[1], buf1, strlen(buf1));
             x1++;
        }
        x1++;
    
        exit(0);
     } else if((cld2_pid = fork()) == 0) {
            close(fd[0]);
            while(x2 < 3) {
                sleep(1);
                sprintf(buf2, "process 2 send message %d. \n", x2);
                write(fd[1], buf2, strlen(buf2));
                x2++;
            }
            x2++;
            
            exit(0);
        }  else if((cld3_pid = fork()) == 0) {
                close(fd[0]);
                while(x3 < 3) {
                    sleep(1);
                    sprintf(buf3, "process 3 send message %d. \n", x3);
                    write(fd[1], buf3, strlen(buf3));
                    x3++;
                }
                x3++;
               // printf("%d\n", x3);
                exit(0);
           }  else {
                  close(fd[1]);
                  while(x1 < 4 || x2 < 4 || x3 < 4) {
                     len = read(fd[0], buf, sizeof(buf));
                     if(len != 0) {
                         buf[len] = 0;
                         printf("Monitor read: %s", buf);
                     }
                  }       
               }
      return 0;
}  

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?