• 进程通信——管道


    在父进程中用pipe()建立一条管道线,往管道里写一句话,两个子进程接收这句话。

     1 #include<unistd.h>
     2 #include<signal.h>
     3 #include<stdio.h>
     4 #include<stdlib.h>
     5 #include<sys/wait.h>
     6 int pid1,pid2;
     7 int main()
     8 {
     9     int fd[2];
    10     char OutPipe[100],InPipe[100];
    11   pipe(fd);
    12      while((pid1=fork())==-1);
    13      if(pid1==0)
    14   { 
    15      lockf(fd[1],1,0);
    16      sprintf(OutPipe,"child 1 process is sending message!");
    17      write(fd[1],OutPipe,50);
    18      sleep(5);
    19      lockf(fd[1],0,0);
    20      exit(0);
    21    }
    22      else
    23   {
    24           while((pid2=fork())==-1);
    25           if(pid2==0)
    26      { 
    27        lockf(fd[1],1,0);
    28        sprintf(OutPipe,"child 2 process is sending message!");
    29        write(fd[1],OutPipe,50);
    30        sleep(5);
    31        lockf(fd[1],0,0);
    32        exit(0);
    33       }
    34           else
    35      {
    36        wait(0);
    37        read(fd[0],InPipe,50);
    38        printf("%s
    ",InPipe);
    39        wait(0);
    40        read(fd[0],InPipe,50);
    41        printf("%s
    ",InPipe);
    42        exit(0);
    43      }
    44   }
    45 }
    #include<unistd.h>
    #include<signal.h>
    #include<stdio.h>
    #include<stdlib.h>
    #include<sys/wait.h>
    int pid1,pid2;
    int main()
    {
        int fd[2];
        char OutPipe[100],OutPipe1[100],InPipe[100];
      pipe(fd);
         while((pid1=fork())==-1);
         if(pid1==0)
      { 
        //   wait(0);
           read(fd[0],InPipe,50);
           printf("pid1:
    %s
    ",InPipe);     
    exit(0);
    // 
       }
         else
      {
              while((pid2=fork())==-1);
              if(pid2==0)
         {
           wait(0);
           read(fd[0],InPipe,50);
           printf("pid2:
    %s
    ",InPipe);
           exit(0);
    //
          }
              else
         {
         lockf(fd[1],1,0);
         sprintf(OutPipe,"child 1 process is sending message!");
         write(fd[1],OutPipe,50);
         sleep(1);
         lockf(fd[1],0,0); 
         sprintf(OutPipe1,"child 2 process is sending message!");
         write(fd[1],OutPipe1,50);
         exit(0);
    //   
         }
      }
    }

  • 相关阅读:
    微服务技术选型
    分布式事务
    微服务架构下的身份认证
    java core
    java web基础知识
    java基础知识学习 内存相关
    java基础知识学习 java异常
    java 基础知识学习 JVM虚拟机参数配置
    java 基础知识学习 内存泄露(memory leak) VS 内存溢出(out of memory)以及内存管理
    【F12】chrome浏览器中 F12 功能的简单介绍
  • 原文地址:https://www.cnblogs.com/WangYiqiang/p/9561780.html
Copyright © 2020-2023  润新知