Linux程序设计笔记-进程间通信

二、进程间通信

1.管道:管道用于相关的进程(特别是父子进程的)间的通讯。使用readwrite进行读写操作。

#include

intpipe(int file_descriptor[2]);       //创建管道

file_desciptor[0]为读取端,file_desciptor[1]为写入端。

 

 例程:

#include

#include

#include

 

intmain(){

    int pipe_buf[2];

    int pid;

    char *buf;

 

    pipe(pipe_buf);

    pid = fork();

   

    buf = (char *)malloc(1024);

    if (!pid){//parent

        sleep(1);

        write(pipe_buf[1],"zhangxiaopeng",sizeof("zhangxiaopeng"));

        printf("PID:%d\n",pid);

        perror("Pipe write");

        printf("writestring:%s\n","zhangxiaopeng");

   

    }else {//child

        sleep(5);

        read(pipe_buf[0],buf,1024);

        printf("PID:%d\n",pid);

        perror("Pipe read");

        printf("readstring:%s\n",buf);

    }

 

    if (pid !=0){

        wait();

    }

}


3. FIFO

1.创建

        程序中创建FIFO

 #include

 #include

 int mkfifo(const char *filename,mode_t mode);

2.打开

程序只能以O_RDONLYO_WRONLYO_NONBLOCK打开。不能读写打开。单向通道。

        如:

   open(const char *path,O_RDONLY);

   //open调用将阻塞,除非有个进程以写方式打开同一个FIFO,否则不会返回。
      open(const char *path,O_RDONLY |O_NONBLOCK);

    //即使没有其他进程以写方式打开FIFO,这个open调用也将成功并立刻返回

         open(constchar *path,O_WRONLY);
         // open调用将阻塞,除非有个进程以读方式打开同一个FIFO为止。

           open(cosnt char *path,O_WRONLY | O_NONBOLOCK);

   //这个函数调用总是立即返回,但如果没有进程以读方式打开FIFO文件,open调用将返回一个错误-1并且FIFO也不会被打开。
        
阻塞的时候,read要等到有数据读才解除阻塞;非阻塞没有数据读时返回0
        
阻塞的时候,write等到有读取进程启动后才继续执行。
         FIFO
文件的长度是一个很重要的因素,系统对任一时间一个FIFO文件里能保存的数据长度有限制最多个数为PIPE_BUF定义在limits.h 

例程:

linux程序设计(第三版)》451


你可能感兴趣的:(linux程序设计)