天天看點

(程序間通信)linux c語言實作匿名管道

 (匿名管道是記憶體上的特殊檔案,命名管道是硬體上的特殊檔案,這個特殊檔案程序結束之後打開沒有東西,共享檔案是硬體上的普通檔案,這個檔案程序結束之後打開可以看到東西)

匿名管道因為沒有“名”,是以隻能用于父子程序間通信。

/***************************************************
##filename      : ampipe.c
##author        : GYZ                               
              
##create time   : 2018-10-18 10:42:01
##last modified : 2018-10-18 11:13:14
##description   : NA                                
***************************************************/
#include <stdio.h>                                  
#include <stdlib.h>                                 
#include <string.h>                                 
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>                                                    
                                                    
int main(int argc,char *argv[])                     
{                                                   
  int pipefd[2];
  char buf[100];
  int ret = 0;
  pid_t fp;
  
  ret = pipe(pipefd);
  if(0 != ret)
  {
    perror("pipe"),exit(0);
  }                        
  fp = fork();
  if(fp < 0)
  {
    perror("fork"),exit(0);
  }   
  else if(0 < fp)
  {
    printf("this is in the father process,write a string to the pipe...\n");
    char str[] = "hi,my child,i am your father";
    write(pipefd[1],str,sizeof(str));
    sleep(1);
    close(pipefd[0]);
    close(pipefd[1]);
  }
  else
  {
    printf("this is in the child process,read a string from the pipe...\n");
    read(pipefd[0],buf,sizeof(buf));
    printf("read : %s\n",buf);
    sleep(1);
    close(pipefd[0]);
    close(pipefd[1]);
  }
  waitpid(fp,NULL,0);                              
  return 0;                                   
}