进程间通讯

进程间通讯(Inter process communication :IPC)

1》6种进程间通讯:

  4种数据共享机制:包括管道(分为无名管道和有名管道),消息队列、共享内存、UNIX域套接字(socket);

  1种实现异步机制:信号;

  1种实现互斥和同步:信号量;

  

  ①、管道(pipe)

    管道是一种特殊的文件;

    管道是文件:可对它使用文件IO的读写函数;

    特殊的:管道是由内核实现的,在内存中文件,它不能使用类似fseek、lseek()的对文件指针的操作;管道是单向的(半双工);

      (1)、无名管道(unnamed pipe):它是用于具有亲缘关系(父子、兄弟进程)的进程间通讯;

              #include <unistd.h>

              int pipe(int pipefd[2]);

          pipefd[0]:固定为读端,pipe[1]:固定为写端;

          RETURN VALUE:On success, zero is returned. On error, -1 is returned, and errno is   set appropriately.

          只有在管道的读端存在时,向管道中写入数据才有意义。否则,向管道中写入数据的进程将收到内核传来的SIGPIPE信号(通常Broken pipe错误)。

      (2)、有名管道:通过特殊的管道文件进行操作,管道文件通过mkfifo创建,它也是内存中的文件,不能用lseek()类似的函数,但可以用一般的文件IO操作函数(open()、read()、write()等)。        

              #include <sys/types.h>
              #include <sys/stat.h>

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

          RETURN VALUE:On success mkfifo() returns 0. In the case of an error, -1 is returned (in which case, errno is set appro‐priately).

        注意:最终创建的管道文件的访问权限为:mode & ~ mask;       

              #include <unistd.h>

              int access(const char *pathname, int mode);

        pathname:文件路径;

        mode:F_OK://判断文件是否存在;  

            R_OK、W_OK、X_OK://判断对文件是否具有读、写、可执行权限(文件必须存在);

 

    ②、信号:

    ③、共享内存和信号量:

 

posted @ 2017-07-24 09:09  hello,123456  阅读(149)  评论(0编辑  收藏  举报