一、Linux 下进程间通讯方式

  1)管道(Pipe)及有名管道(named pipe):

  管道可用于具有亲缘关系进程间的通信,有名管道克服了管道没有名字的限制,因此,除具有管道所具有的功能外,它还允许无亲缘关系进程间的通信;

  2)无名信号量(semaphore)级有名信号量(named semaphore):

  主要作为进程间以及同一进程不同线程之间的同步手段。

  3)信号(Signal)

  信号是比较复杂的通信方式,用于通知接受进程有某种事件生,除了用于进程间通信外,进程还可以发送信号给进程本身;linux除了支持Unix早期 信号语义函数sigal外,还支持语义符合Posix.1标准的信号函数sigaction(实际上, 该函数是基于BSD的,BSD为了实现可靠信号机制,又能够统一对外接口,sigaction函数重新实现了signal函数);

4)报文(Message)队列(消息队列)

  消息队列是消息的链接表,包括Posix消息队列system V消息队列。有足够权限的进程可以向队列中添加消息,被赋予读权限的进程则可以读走队列中的消息。消息队列克服了信号承载信息量少,管道只能承载无格式字节流以及缓冲区大小受限等缺点。

 5)共享内存

  使得多个进程可以访问同一块内存空间,是最快的可用IPC形式。是针其他通信机制运行效率较低设计的。往往与其它通信机制,如信号量结合使用, 来达到进程间的同步及互斥。

 6)套接字(Socket)

  更为一般的进程间通信机制,可用于不同机器之间的进程间通信。起初是由Unix系统的BSD分支开发出来的,但现在一般可以移植到其它类Unix 系统上:Linux和System V的变种都支持套接字。

二、进程间通讯特点说明

1. socket
        1、使用socket通信的方式实现起来简单,可以使用因特网域和UNIX域来实现,使用因特网域可以实现不同主机之间的进出通信。
        2、该方式自身携带同步机制,不需要额外的方式来辅助实现同步。
        3、随进程持续。
2. 共享内存
        1、最快的一种通信方式,多个进程可同时访问同一片内存空间,相对其他方式来说具有更少的数据拷贝,效率较高。
        2、需要结合信号灯或其他方式来实现多个进程间同步,自身不具备同步机制。
        3、随内核持续,相比于随进程持续生命力更强。
3. 管道
        1、较早的一种通信方式,缺点明显:只能用于有亲缘关系进程之间的通信;只支持单向数据流,如果要双向通信需要多创建一个管道来实现。
        2、自身具备同步机制。
        3、随进程持续。
4. FIFO
        1、是有名管道,所以支持没有亲缘关系的进程通信。和共享内存类似,提供一个路径名字将各个无亲缘关系的进程关联起来。但是也需要创建两个描述符来实现双向通信。
        2、自身具备同步机制。
        3、随进程持续。
5. 信号
        1、这种通信可携带的信息极少。不适合需要经常携带数据的通信。
        2、不具备同步机制,类似于中断,什么时候产生信号,进程是不知道的。
6. 消息队列
        1、与共享内存和FIFO类似,使用一个路径名来实现各个无亲缘关系进程之间的通信。消息队列相比于其他方式有很多优点:它提供有格式的字节流,减少了开发人员的工作量;消息具有类型(system V)或优先级(posix)。其他方式都没有这些优点。
        1、具备同步机制。
        2、随内核持续。

三、进程间通讯实现方式

  1、有名管道(不相关的没有血缘关系的进程也可以相互通信)

  1. 、管道创建
  2. #include <sys/types.h>
  3. #include <sys/stat.h>
  4. int mkfifo(const char *filename, mode_t mode);
  5. int mknod(const char *filename, mode_t mode | S_IFIFO, (dev_t));
  6.  
  7. filname是指文件名,而mode是指定文件的读写权限。mknod是比较老的函数,而使用mkfifo函数更加简单和规范,所以建议用mkfifo
  8.  
  9. open(const char *path, O_RDONLY);//
  10. open(const char *path, O_RDONLY | O_NONBLOCK);//
  11. open(const char *path, O_WRONLY);//
  12. open(const char *path, O_WRONLY | O_NONBLOCK);//
  1. 、写入端代码
  2. #include <unistd.h>
  3. #include <stdlib.h>
  4. #include <fcntl.h>
  5. #include <limits.h>
  6. #include <sys/types.h>
  7. #include <sys/stat.h>
  8. #include <stdio.h>
  9. #include <string.h>
  10.  
  11. int main()
  12. {
  13. const char *fifo_name = "/tmp/my_fifo";
  14. int pipe_fd = -;
  15. int data_fd = -;
  16. int res = ;
  17. const int open_mode = O_WRONLY;
  18. int bytes_sent = ;
  19. char buffer[PIPE_BUF + ];
  20. int bytes_read = ;
  21.  
  22. if(access(fifo_name, F_OK) == -)
  23. {
  24. printf ("Create the fifo pipe.\n");
  25. res = mkfifo(fifo_name, );
  26.  
  27. if(res != )
  28. {
  29. fprintf(stderr, "Could not create fifo %s\n", fifo_name);
  30. exit(EXIT_FAILURE);
  31. }
  32. }
  33.  
  34. printf("Process %d opening FIFO O_WRONLY\n", getpid());
  35. pipe_fd = open(fifo_name, open_mode);
  36. printf("Process %d result %d\n", getpid(), pipe_fd);
  37.  
  38. if(pipe_fd != -)
  39. {
  40. bytes_read = ;
  41. data_fd = open("Data.txt", O_RDONLY);
  42. if (data_fd == -)
  43. {
  44. close(pipe_fd);
  45. fprintf (stderr, "Open file[Data.txt] failed\n");
  46. return -;
  47. }
  48.  
  49. bytes_read = read(data_fd, buffer, PIPE_BUF);
  50. buffer[bytes_read] = '\0';
  51. while(bytes_read > )
  52. {
  53.  
  54. res = write(pipe_fd, buffer, bytes_read);
  55. if(res == -)
  56. {
  57. fprintf(stderr, "Write error on pipe\n");
  58. exit(EXIT_FAILURE);
  59. }
  60.  
  61. bytes_sent += res;
  62. bytes_read = read(data_fd, buffer, PIPE_BUF);
  63. buffer[bytes_read] = '\0';
  64. }
  65.  
  66. close(pipe_fd);
  67. close(data_fd);
  68. }
  69. else
  70. exit(EXIT_FAILURE);
  71.  
  72. printf("Process %d finished\n", getpid());
  73. exit(EXIT_SUCCESS);
  74. }
  1. 管道读取端
  2. #include <unistd.h>
  3. #include <stdlib.h>
  4. #include <stdio.h>
  5. #include <fcntl.h>
  6. #include <sys/types.h>
  7. #include <sys/stat.h>
  8. #include <limits.h>
  9. #include <string.h>
  10.  
  11. int main()
  12. {
  13. const char *fifo_name = "/tmp/my_fifo";
  14. int pipe_fd = -;
  15. int data_fd = -;
  16. int res = ;
  17. int open_mode = O_RDONLY;
  18. char buffer[PIPE_BUF + ];
  19. int bytes_read = ;
  20. int bytes_write = ;
  21.  
  22. memset(buffer, '\0', sizeof(buffer));
  23.  
  24. printf("Process %d opening FIFO O_RDONLY\n", getpid());
  25. pipe_fd = open(fifo_name, open_mode);
  26. data_fd = open("DataFormFIFO.txt", O_WRONLY|O_CREAT, );
  27.  
  28. if (data_fd == -)
  29. {
  30. fprintf(stderr, "Open file[DataFormFIFO.txt] failed\n");
  31. close(pipe_fd);
  32. return -;
  33. }
  34.  
  35. printf("Process %d result %d\n",getpid(), pipe_fd);
  36. if(pipe_fd != -)
  37. {
  38. do
  39. {
  40. res = read(pipe_fd, buffer, PIPE_BUF);
  41. bytes_write = write(data_fd, buffer, res);
  42. bytes_read += res;
  43. }while(res > );
  44.  
  45. close(pipe_fd);
  46. close(data_fd);
  47. }
  48. else
  49. exit(EXIT_FAILURE);
  50.  
  51. printf("Process %d finished, %d bytes read\n", getpid(), bytes_read);
  52. exit(EXIT_SUCCESS);
  53. }

 2、无名管道(只能用于有血缘关系的进程之间,例如父子进程之间)

  1. #include<unistd.h>
  2. int pipe(pipefd[]);
  3. pipefd[]//用来返回文件描述符的数组
  4. pipefd[]//为读打开,为读端
  5. pipefd[]//为写打开,为写端
  6. //通常调用pipe()之后会调用fork进行创建父子进程,进行通信,对于管道数据的流向,要么父进程(写,关闭读端),子进程(读,关闭写端),要么子进程(写,关闭读端),父进程(读,关闭写端),在此之间,双方可以调用read(对于读进程)和write(对于写进程)对未关闭的文件描述符进行读写操作
  7. //读写规则 1、读一个写端关闭的管道,在所有数据读完之后,read返回0,以指示文件到结尾处 2、如果写一个读端已关闭的管道,则产生SIGPIPE信号,捕捉信号write出错返回 3、互斥与原子性,在写的时候,读端不允许访问管道,并且已写尚未读取的字节数应该小于或等于PIPE_BUF(一般为4096字节)所规定的缓存大小
  8. //当所有的读端与写端全部关闭后,管道才能被销毁
  1. 样例:
  2. #include <stdio.h>
  3. #include <sys/wait.h>
  4. #include <unistd.h>
  5. #include <stdlib.h>
  6. #include <string.h>
  7. int main()
  8. {
  9. int pipefd[];//创建之后返回两个文件描述符pipefd[0]--读端 pipefd[2]--写端
  10. pid_t cpid;
  11. char buf;
  12. if (pipe(pipefd) == -)//创建管道
  13. {
  14. perror("pipe");
  15. exit(EXIT_FAILURE);
  16. }
  17. cpid = fork();//创建子进程
  18. if (cpid<)
  19. {
  20. perror("fork cpid error");
  21. exit(EXIT_FAILURE);
  22. }
  23. if (cpid == )//child
  24. {
  25. close(pipefd[]);//关闭文件描述符0,读端
  26. int i = ;
  27. char* _mesg = NULL;
  28. while (i<)
  29. {
  30. _mesg = "hello father ! i am child.\n ";
  31. write(pipefd[], _mesg, strlen(_mesg)+);
  32. sleep();
  33. i++;
  34. }
  35. }
  36. else//father
  37. {
  38. close(pipefd[]);//父进程将argv[1]写入管道,关闭读端
  39. char _mesg_f[];
  40. int j = ;
  41. while (j < )
  42. {
  43. memset(_mesg_f, '\0', sizeof(_mesg_f));
  44. read(pipefd[], _mesg_f, sizeof(_mesg_f));
  45. sleep();
  46. printf("%s\n", _mesg_f);
  47. j++;
  48. }
  49. }
  50. return ;
  51. }

 3、有名信号量

  1. #include <fcntl.h>
  2. #include <sys/stat.h>
  3. #include <semaphore.h>
  4. sem_t *sem_open(const char *name, int oflag); //打开一个有名信号量,此时有名信号量是已经存在了的。
  5. sem_t *sem_open(const char *name, int oflag, mode_t mode, unsigned int value);//创建有名信号量
  6. 参数说明:
  7. name:信号量文件名。
  8. flagssem_open() 函数的行为标志。
  9. mode:文件权限,可用八进制表示,如0777.
  10. value:信号量初始值。
  11.  
  12. sem_close函数
  13. #include <semaphore.h>
  14. int sem_close(sem_t *sem);//关闭有名信号量
  15. 返回值:若成功,返回0;若出错,返回-
  16. 参数:
  17. sem:指向信号量的指针。
  18.  
  19. sem_unlink函数
  20. #include <semaphore.h>
  21. int sem_unlink(const char *name);//删除有名信号量文件
  22. 返回值:若成功,返回0;若出错,返回-
  23. 参数:
  24.  
  25. name:有名信号量文件名
  26.  
  27. sem_open 用于创建一个信号量,并能初始化它的值。
  28. sem_wait sem_trywait 相当于 P 操作,它们都能将信号量的值减一,两者的区别在于若信号量小于零时,sem_wait 将会阻塞进程,而 sem_trywait 则会立即返回。
  29. sem_post   相当于 V 操作,它将信号量的值加一同时发出信号唤醒等待的进程。
  30. sem_getvalue 获取信号量的值。
  31. sem_close sem_unlink 删除信号量
  1. #include <unistd.h>
  2. #include <stdio.h>
  3. #include<stdlib.h>
  4. #include <sys/types.h>
  5. #include <sys/stat.h>
  6. #include <fcntl.h>
  7. #include <pthread.h>
  8. #include <semaphore.h>
  9. #define FILENAME "name_sem_file"
  10. int main ()
  11. {
  12. sem_t *sem = NULL;
  13. //有名信号量在fork子程序中继承下来
  14. //跟open()打开方式很相似,不同进程只要名字一样,那么打开的就是同一个有名信号量
  15. sem = sem_open("name_sem", O_CREAT|O_RDWR, , ); //信号量值为 1
  16. if(sem == SEM_FAILED)
  17. {
  18. perror("sem_open");
  19. exit(-);
  20. }
  21. pid_t pid; //pid表示fork函数返回的值
  22. int count=;
  23. int fd = open(FILENAME,O_RDWR | O_CREAT,);
  24. if(fd < )
  25. {
  26. perror("open");
  27. }
  28. if ((pid = fork()) < )
  29. {
  30. perror("fork");
  31. exit(-);
  32. }
  33. else if (pid == )
  34. {
  35. char write_buf[] = "";
  36. int i = ;
  37. printf("child: pid = %ld,ppid = %ld, fd = %d, count = %d\n",(long)getpid(),(long)getppid(),fd,count);
  38. for(i = ;i < ;i++)
  39. {
  40. /*信号量减一,P 操作*/
  41. sem_wait(sem);
  42. for(i = ;i<;i++)
  43. {
  44. if (write(fd,write_buf,sizeof(write_buf)))
  45. {
  46. perror("write");
  47. }
  48. count++;
  49. }
  50. printf("in child....and count = %d\n",count);
  51. /*信号量加一,V 操作*/
  52. sem_post(sem);
  53. sleep();
  54. }
  55. exit();
  56. }
  57. else
  58. {
  59. char write_buf[] = "";
  60. int i = ;
  61. printf("parent: pid = %ld,ppid = %ld, fd = %d, count = %d\n",(long)getpid(),(long)getppid(),fd,count);
  62. for(i = ; i<; i++)
  63. {
  64. /*信号量减一,P 操作*/
  65. sem_wait(sem);
  66. for(i = ;i<;i++)
  67. {
  68. if (write(fd,write_buf,sizeof(write_buf)))
  69. {
  70. perror("write");
  71. }
  72. count++;
  73. }
  74. printf("in father.... count = %d\n",count);
  75. /*信号量加一,V 操作*/
  76. sem_post(sem);
  77. sleep();
  78. }
  79. printf("Waiting for the child process to exit\n");
  80. //等待子进程退出
  81. waitpid(pid,NULL,);
  82. sem_del("name_sem"); //删除信号量文件 name_sem
  83. exit();
  84.  
  85. }
  86. //return 0;
  87. }
  1. #include <unistd.h>
  2. #include <stdio.h>
  3. #include<stdlib.h>
  4. #include <sys/types.h>
  5. #include <sys/stat.h>
  6. #include <fcntl.h>
  7. #include <pthread.h>
  8. #include <semaphore.h>
  9. #define FILENAME "sync_name_sem_file"
  10.  
  11. int main ()
  12. {
  13. sem_t *sem_1 = NULL;
  14. sem_t *sem_2 = NULL;
  15. //有名信号量在fork子程序中继承下来
  16. //跟open()打开方式很相似,不同进程只要名字一样,那么打开的就是同一个有名信号量
  17. sem_1 = sem_open("sync_name_sem_1", O_CREAT|O_RDWR, , ); //信号量值为 0
  18. sem_2 = sem_open("sync_name_sem_2", O_CREAT|O_RDWR, , ); //信号量值为 1
  19. if( (sem_1 == SEM_FAILED) | (sem_2 == SEM_FAILED))
  20. {
  21. perror("sem_open");
  22. exit(-);
  23. }
  24. pid_t pid; //pid表示fork函数返回的值
  25. int count=;
  26. int fd = open(FILENAME,O_RDWR | O_CREAT,);
  27. if(fd < )
  28. {
  29. perror("open");
  30. }
  31. if ((pid = fork()) < )
  32. {
  33. perror("fork");
  34. exit(-);
  35. }
  36. else if (pid == )
  37. {
  38. char write_buf[] = "";
  39. int i = ;
  40. printf("child: pid = %ld,ppid = %ld, fd = %d, count = %d\n",(long)getpid(),(long)getppid(),fd,count);
  41. for(i = ;i<;i++)
  42. {
  43. /*信号量减一,P 操作*/
  44. sem_wait(sem_1);
  45. for(i = ;i<;i++)
  46. {
  47. if (write(fd,write_buf,sizeof(write_buf)))
  48. {
  49. perror("write");
  50. }
  51. count++;
  52. }
  53. printf("in child....and count = %d\n",count);
  54. /*信号量加一,V 操作*/
  55. sem_post(sem_2);
  56. sleep()
  57. }
  58. exit();
  59. }
  60. else
  61. {
  62. char write_buf[] = "";
  63. int i = ;
  64. printf("parent: pid = %ld,ppid = %ld, fd = %d, count = %d\n",(long)getpid(),(long)getppid(),fd,count);
  65. for(i = ;i<;i++)
  66. {
  67. /*信号量减一,P 操作*/
  68. sem_wait(sem_2);
  69. for(i = ;i<;i++)
  70. {
  71. if (write(fd,write_buf,sizeof(write_buf)))
  72. {
  73. perror("write");
  74. }
  75. count++;
  76. }
  77. printf("in father.... count = %d\n",count);
  78. /*信号量加一,V 操作*/
  79. sem_post(sem_1);
  80. sleep();
  81. }
  82. printf("Waiting for the child process to exit\n");
  83. //等待子进程退出
  84. waitpid(pid,NULL,);
  85. sem_del("sync_name_sem_1"); //删除信号量文件 sync_name_sem_1
  86. sem_del("sync_name_sem_2"); //删除信号量文件 sync_name_sem_2
  87. exit();
  88. }
  89. //return 0;
  90. }

4、无名信号量 

  1. )初始化创建信号量
  2. int sem_init(sem_t *sem, int pshared, unsigned int value);
  3. 参数:
  4. sem:信号量的地址。
  5. pshared:等于 ,信号量在线程间共享(常用);不等于0,信号量在进程间共享。
  6. value:信号量的初始值
  7. )信号量 P 操作(减
  8. int sem_wait(sem_t *sem);
  9. 参数:
  10. sem:信号量的地址。
  11. int sem_trywait(sem_t *sem); //以非阻塞的方式来对信号量进行减 1 操作。若操作前,信号量的值等于 0,则对信号量的操作失败,函数立即返回。
  12. )信号量 V 操作(加
  13. int sem_post(sem_t *sem);
  14. 参数:
  15. sem:信号量的地址。
  16. )获取信号量的值
  17. int sem_getvalue(sem_t *sem, int *sval);
  18. 参数:
  19. sem:信号量地址。
  20. sval:保存信号量值的地址。
  21. )销毁信号量
  22. int sem_destroy(sem_t *sem);
  23. 参数:
  24. sem:信号量地址。
  1. 信号量用于互斥实例:
  2. #include <stdio.h>
  3. #include <pthread.h>
  4. #include <unistd.h>
  5. #include <semaphore.h>
  6.  
  7. sem_t sem; //信号量
  8.  
  9. void printer(char *str)
  10. {
  11. sem_wait(&sem);//减一
  12. while(*str)
  13. {
  14. putchar(*str);
  15. fflush(stdout);
  16. str++;
  17. sleep();
  18. }
  19. printf("\n");
  20.  
  21. sem_post(&sem);//加一
  22. }
  23.  
  24. void *thread_fun1(void *arg)
  25. {
  26. char *str1 = "hello";
  27. printer(str1);
  28. }
  29.  
  30. void *thread_fun2(void *arg)
  31. {
  32. char *str2 = "world";
  33. printer(str2);
  34. }
  35.  
  36. int main(void)
  37. {
  38. pthread_t tid1, tid2;
  39.  
  40. sem_init(&sem, , ); //初始化信号量,初始值为 1
  41.  
  42. //创建 2 个线程
  43. pthread_create(&tid1, NULL, thread_fun1, NULL);
  44. pthread_create(&tid2, NULL, thread_fun2, NULL);
  45.  
  46. //等待线程结束,回收其资源
  47. pthread_join(tid1, NULL);
  48. pthread_join(tid2, NULL);
  49.  
  50. sem_destroy(&sem); //销毁信号量
  51.  
  52. return ;
  53. }
  1. 信号量用于同步实例:
  2. #include <stdio.h>
  3. #include <unistd.h>
  4. #include <pthread.h>
  5. #include <semaphore.h>
  6.  
  7. sem_t sem_g,sem_p; //定义两个信号量
  8. char ch = 'a';
  9.  
  10. void *pthread_g(void *arg) //此线程改变字符ch的值
  11. {
  12. while()
  13. {
  14. sem_wait(&sem_g);
  15. ch++;
  16. sleep();
  17. sem_post(&sem_p);
  18. }
  19. }
  20.  
  21. void *pthread_p(void *arg) //此线程打印ch的值
  22. {
  23. while()
  24. {
  25. sem_wait(&sem_p);
  26. printf("%c",ch);
  27. fflush(stdout);
  28. sem_post(&sem_g);
  29. }
  30. }
  31.  
  32. int main(int argc, char *argv[])
  33. {
  34. pthread_t tid1,tid2;
  35. sem_init(&sem_g, , ); //初始化信号量
  36. sem_init(&sem_p, , );
  37.  
  38. pthread_create(&tid1, NULL, pthread_g, NULL);
  39. pthread_create(&tid2, NULL, pthread_p, NULL);
  40.  
  41. pthread_join(tid1, NULL);
  42. pthread_join(tid2, NULL);
  43.  
  44. return ;
  45. }

5、信号

  1. SIGHUP A 终端挂起或者控制进程终止
  2.  
  3. SIGINT A 键盘中断(如break键被按下)
  4.  
  5. SIGQUIT C 键盘的退出键被按下
  6.  
  7. SIGILL C 非法指令
  8.  
  9. SIGABRT C abort()发出的退出指令
  10.  
  11. SIGFPE C 浮点异常
  12.  
  13. SIGKILL AEF Kill信号
  14.  
  15. SIGSEGV C 无效的内存引用
  16.  
  17. SIGPIPE A 管道破裂: 写一个没有读端口的管道
  18.  
  19. SIGALRM A alarm()发出的信号
  20.  
  21. SIGTERM A 终止信号
  22.  
  23. SIGUSR1 ,, A 用户自定义信号1
  24.  
  25. SIGUSR2 ,, A 用户自定义信号2
  26.  
  27. SIGCHLD ,, B 子进程结束信号
  28.  
  29. SIGCONT ,, 进程继续(曾被停止的进程)
  30.  
  31. SIGSTOP ,, DEF 终止进程
  32.  
  33. SIGTSTP ,, D 控制终端(tty)上按下停止键
  34.  
  35. SIGTTIN ,, D 后台进程企图从控制终端读
  36.  
  37. SIGTTOU ,, D 后台进程企图从控制终端写
  1. 样例:
  2. void sigroutine(int signo) {
  3.  
  4. switch (signo) {
  5.  
  6. case SIGALRM:
  7.  
  8. printf("Catch a signal -- SIGALRM ");
  9.  
  10. break;
  11.  
  12. case SIGVTALRM:
  13.  
  14. printf("Catch a signal -- SIGVTALRM ");
  15.  
  16. break;
  17.  
  18. }
  19.  
  20. return;
  21.  
  22. }
  23.  
  24. int main()
  25.  
  26. {
  27.  
  28. struct itimerval value,ovalue,value2;
  29.  
  30. sec = ;
  31.  
  32. printf("process id is %d ",getpid());
  33.  
  34. signal(SIGALRM, sigroutine);
  35.  
  36. signal(SIGVTALRM, sigroutine);
  37.  
  38. value.it_value.tv_sec = ;
  39.  
  40. value.it_value.tv_usec = ;
  41.  
  42. value.it_interval.tv_sec = ;
  43.  
  44. value.it_interval.tv_usec = ;
  45.  
  46. setitimer(ITIMER_REAL, &value, &ovalue);
  47.  
  48. value2.it_value.tv_sec = ;
  49.  
  50. value2.it_value.tv_usec = ;
  51.  
  52. value2.it_interval.tv_sec = ;
  53.  
  54. value2.it_interval.tv_usec = ;
  55.  
  56. setitimer(ITIMER_VIRTUAL, &value2, &ovalue);
  57.  
  58. for (;;) ;
  59.  
  60. }

6、共享内存

  1. shmget
  2. #include <sys/ipc.h>
  3. #include <sys/shm.h>
  4. int shmget(key_t key, size_t size, int shmflg);
  5. 函数说明:得到一个共享内存标识符或创建一个共享内存对象并返回共享内存标识符。
  6. 参数:
  7. key ftok函数返回的I P C键值
  8. size 大于0的整数,新建的共享内存大小,以字节为单位,获取已存在的共享内存块标识符时,该参数为0,
  9. shmflg IPC_CREAT||IPC_EXCL 执行成功,保证返回一个新的共享内存标识符,附加参数指定IPC对象存储权限,如|
  10. 返回值:成功返回共享内存的标识符,出错返回-,并设置error错误位。
  11.  
  12. shmat
  13. #include <sys/types.h>
  14. #include <sys/shm.h>
  15. void *shmat(int shmid, const void shmaddr, int shmflg);
  16.  
  17. 函数说明:连接共享内存标识符为shmid的共享内存,连接成功后把共享内存区对象映射到调用进程的地址空间
  18. 参数:
  19. shmid 共享内存标识符
  20. shmaddr 指定共享内存出现在进程内存地址的什么位置,通常指定为NULL,让内核自己选择一个合适的地址位置
  21. shmflg SHM_RDONLY 为只读模式,其他参数为读写模式
  22. 返回值:成功返回附加好的共享内存地址,出错返回-,并设置error错误位
  23.  
  24. shmdt
  25. #include <sys/types.h>
  26. #include <sys/shm.h>
  27. void *shmdt(const void* shmaddr);
  28.  
  29. 函数说明:与shmat函数相反,是用来断开与共享内存附加点的地址,禁止本进程访问此片共享内存,需要注意的是,该函数并不删除所指定的共享内存区,而是将之前用shmat函数连接好的共享内存区脱离目前的进程
  30. 参数:shmddr 连接共享内存的起始地址
  31. 返回值:成功返回0,出错返回-,并设置error
  32.  
  33. shmctl
  34. #include <sys/types.h>
  35. #Include <sys/shm.h>
  36. int shmctl(int shmid, int cmd, struct shmid_ds* buf);
  37. 函数说明:控制共享内存块
  38. 参数:
  39. shmid:共享内存标识符
  40. cmd
  41. IPC_STAT:得到共享内存的状态,把共享内存的shmid_ds结构赋值到buf所指向的buf
  42. IPC_SET:改变共享内存的状态,把buf所指向的shmid_ds结构中的uidgidmode赋值到共享内存的shmid_ds结构内
  43. IPC_RMID:删除这块共享内存
  44. buf:共享内存管理结构体
  45. 返回值:成功返回0,出错返回-,并设置error错误位。
  1. comm.h
  2.  
  3. #ifndef _COMM_H_
  4. #define _COMM_H_
  5.  
  6. #include <stdio.h>
  7. #include <sys/types.h>
  8. #include <sys/ipc.h>
  9. #include <sys/shm.h>
  10. #define PATHNAME "." // ftok函数 生成key使用
  11. #define PROJ_ID 66 // ftok 函数生成key使用
  12. int create_shm( int size);// 分配指定大小的共享内存块
  13. int destroy_shm( int shmid); // 释放指定id的共享内存块
  14. int get_shmid(); // 获取已经存在的共享内存块
  15.  
  16. #endif /*_COMM_H_*/
  1. #include "comm.h"
  2.  
  3. //
  4. static int comm_shm(int size, int shmflag)
  5. {
  6. key_t key = ftok(PATHNAME, PROJ_ID); // 获取key
  7. if(key < ){
  8. perror("ftok");
  9. return -;
  10. }
  11. int shmid = shmget(key, size, shmflag);
  12. if(shmid < ){
  13. perror("shmget");
  14. return -;
  15. }
  16. return shmid;
  17. }
  18. int create_shm( int size
  19. {
  20. return comm_shm(size, IPC_CREAT|IPC_EXCL|);
  21. }
  22.  
  23. int get_shmid()
  24. {
  25. return comm_shm(, IPC_CREAT);
  26. }
  27. int destroy_shm(int shmid)
  28. {
  29. if( shmctl( shmid, IPC_RMID, NULL) < )
  30. {
  31. perror("shmctl");
  32. return -;
  33. }
  34. return ;
  35. }
  1. server.c
  2.  
  3. #include "comm.h"
  4.  
  5. int main()
  6. {
  7. int shmid = create_shm();// 创建共享内存块
  8. char *buf;
  9. int i = ;
  10. buf = shmat(shmid,NULL, );
  11. while( i < )
  12. {
  13. buf[i] = 'a'+i ;
  14. i++;
  15. sleep();
  16. if(i == )
  17. break; // 让程序结束,去释放该共享内存
  18. }
  19. destroy_shm(shmid);
  20. return ;
  21. }
  1. clinet.c
  2.  
  3. #include "comm.h"
  4.  
  5. int main()
  6. {
  7. int shmid = get_shmid();
  8. char *buf;
  9. int index = ;
  10. buf = shmat(shmid,NULL, );
  11. while( index < )
  12. {
  13. printf("%s\n", buf);
  14. sleep();
  15. index++;
  16. if( index == )
  17. break; // 让程序结束
  18. }
  19. return ;
  20. }

7、消息队列

  1. 函数功能介绍
  2. msgget函数
  3. #include <sys/types.h>
  4. #include <sys/ipc.h>
  5. #include <sys/msg.h>
  6. int msgget(key_t key, int msgflg);
  7.  
  8. 功能:创建或取得一个消息队列对象
  9. 返回:消息队列对象的id 同一个key得到同一个对象
  10. 格式:msgget(key,flag|mode);
  11. flag:可以是0或者IPC_CREAT(不存在就创建)
  12. mode:同文件权限一样
  13.  
  14. msgsnd函数
  15. int msgsnd(int msqid, const void *msgp, size_t msgsz, int msgflg);
  16. 功能:将msgp消息写入标识为msgid的消息队列
  17. msgp
  18. struct msgbuf {
  19. long mtype; /* message type, must be > 0 */消息的类型必须>
  20. char mtext[]; /* message data */长度随意
  21. };
  22.  
  23. msgsz:要发送的消息的大小 不包括消息的类型占用的4个字节
  24. msgflg 如果是0 当消息队列为满 msgsnd会阻塞
  25. 如果是IPC_NOWAIT 当消息队列为满时 不阻塞 立即返回
  26. 返回值:成功返回id 失败返回-
  27.  
  28. msgrcv函数
  29. ssize_t msgrcv(int msqid, void *msgp, size_t msgsz, long msgtyp,
  30. int msgflg);
  31. 功能:从标识符为msgid的消息队列里接收一个指定类型的消息 存储于msgp 读取后 把消息从消息队列中删除
  32. msgtyp:为 表示无论什么类型 都可以接收
  33. msgp:存放消息的结构体
  34. msgsz:要接收的消息的大小 不包含消息类型占用的4字节
  35. msgflg:如果是0 标识如果没有指定类型的消息 就一直等待
  36. 如果是IPC_NOWAIT 则表示不等待
  37.  
  38. msgctl函数
  39. int msgctl(int msqid, int cmd, struct msqid_ds *buf);
  40. msgctl(msgid,IPC_RMIDNULL);//删除消息队列对象
  1. 接收模块
  2.  
  3. /*=============================================================================
  4. # FileName: msgreceive.c
  5. # Desc: receice message from message queue
  6. # Author: Licaibiao
  7. # Version:
  8. # LastChange: 2017-01-20
  9. # History:
  10. =============================================================================*/
  11.  
  12. #include <unistd.h>
  13. #include <stdlib.h>
  14. #include <stdio.h>
  15. #include <string.h>
  16. #include <errno.h>
  17. #include <sys/msg.h>
  18.  
  19. struct msg_st
  20. {
  21. long int msg_type;
  22. char text[];
  23. };
  24.  
  25. int main()
  26. {
  27. int running = ;
  28. int msgid = -;
  29. int len = ;
  30. long int msgtype = ;
  31. struct msg_st data;
  32.  
  33. msgid = msgget((key_t), | IPC_CREAT);
  34. if(- == msgid )
  35. {
  36. fprintf(stderr, "msgget failed with error: %d\n", errno);
  37. exit(EXIT_FAILURE);
  38. }
  39.  
  40. while(running)
  41. {
  42. memset(&data.text, , );
  43. len = msgrcv(msgid, (void*)&data, , msgtype, );
  44. if(- == len)
  45. {
  46. fprintf(stderr, "msgrcv failed with errno: %d\n", errno);
  47. exit(EXIT_FAILURE);
  48. }
  49. printf("You wrote: %s\n",data.text);
  50.  
  51. if( == strncmp(data.text, "end", ))
  52. running = ;
  53. }
  54.  
  55. //remove message queue
  56. if(- == msgctl(msgid, IPC_RMID, ))
  57. {
  58. fprintf(stderr, "msgctl(IPC_RMID) failed\n");
  59. exit(EXIT_FAILURE);
  60. }
  61. exit(EXIT_SUCCESS);
  62. }
  1. 发送模块
  2. /*=============================================================================
  3. # FileName: msgsend.c
  4. # Desc: send data to message queue
  5. # Author: Licaibiao
  6. # Version:
  7. # LastChange: 2017-01-20
  8. # History:
  9. =============================================================================*/
  10.  
  11. #include <unistd.h>
  12. #include <stdlib.h>
  13. #include <stdio.h>
  14. #include <string.h>
  15. #include <sys/msg.h>
  16. #include <errno.h>
  17.  
  18. #define MAX_TEXT 512
  19. struct msg_st
  20. {
  21. long int msg_type;
  22. char text[MAX_TEXT];
  23. };
  24.  
  25. int main()
  26. {
  27. int running = ;
  28. struct msg_st data;
  29. char buffer[BUFSIZ];
  30. int msgid = -;
  31. int len;
  32.  
  33. msgid = msgget((key_t), | IPC_CREAT);
  34. if(msgid == -)
  35. {
  36. fprintf(stderr, "msgget failed with error: %d\n", errno);
  37. exit(EXIT_FAILURE);
  38. }
  39.  
  40. while(running)
  41. {
  42.  
  43. printf("Enter data : ");
  44. fgets(buffer, BUFSIZ, stdin);
  45. data.msg_type = ;
  46. strcpy(data.text, buffer);
  47. len = strlen(data.text);
  48. if(msgsnd(msgid, (void*)&data, len-, ) == -)
  49. {
  50. fprintf(stderr, "msgsnd failed\n");
  51. exit(EXIT_FAILURE);
  52. }
  53.  
  54. if(strncmp(buffer, "end", ) == )
  55. running = ;
  56. usleep();
  57. }
  58. exit(EXIT_SUCCESS);
  59. }

 三、补充

  1、多进程与多线程区别

对比维度 多进程 多线程 总结
数据共享、同步 数据共享复杂,需要用IPC;数据是分开的,同步简单 因为共享进程数据,数据共享简单,但也是因为这个原因导致同步复杂 各有优势
内存、CPU 占用内存多,切换复杂,CPU利用率低 占用内存少,切换简单,CPU利用率高 线程占优
创建销毁、切换 创建销毁、切换复杂,速度慢  创建销毁、切换简单,速度很快  线程占优
 编程、调试  编程简单,调试简单  编程复杂,调试复杂  进程占优
 可靠性  进程间不会互相影响  一个线程挂掉将导致整个进程挂掉  进程占优
 分布式  适应于多核、多机分布式;如果一台机器不够,扩展到多台机器比较简单

  

Linux 进程间通讯的更多相关文章

  1. Linux 进程间通讯方式 pipe()函数 (转载)

    转自:http://blog.csdn.net/ta893115871/article/details/7478779 Linux 进程间通讯方式有以下几种: 1->管道(pipe)和有名管道( ...

  2. Linux 进程间通讯详解一

    进程间的通讯 两台主机间的进程通讯 --socket 一台主机间的进程通讯 --管道(匿名管道,有名管道) --System V进程间通信(IPC)包括System V消息队列,System V信号量 ...

  3. linux进程间通讯-System V IPC 信号量

    进程间通信的机制--信号量.注意请不要把它与之前所说的信号混淆起来,信号与信号量是不同的两种事物.有关信号的很多其它内容,能够阅读我的还有一篇文章:Linux进程间通信--使用信号.以下就进入信号量的 ...

  4. Linux 进程间通讯详解二

    消息队列 --消息队列提供了本机上从一个进程向另外一个进程发送一块数据的方法 --每个数据块都被认为有一个类型,接收者进程接收的数据块可以有不同的类型值 --消息队列也有管道一样的不足,就是每个消息的 ...

  5. Linux进程间通讯的几种方式的特点和优缺点,和适用场合

    http://blog.csdn.net/jeffcjl/article/details/5523569 由于不同的进程运行在各自不同的内存空间中.一方对于变量的修改另一方是无法感知的.因此.进程之间 ...

  6. linux进程间通讯的几种方式的特点和优缺点

    # 管道( pipe ):管道是一种半双工的通信方式,数据只能单向流动,而且只能在具有亲缘关系的进程间使用.进程的亲缘关系通常是指父子进程关系.# 有名管道 (named pipe) : 有名管道也是 ...

  7. Linux 进程间通讯详解七

    上图的一台主机服务器架构的重大缺陷是容易死锁 因为客户端,服务器都往同一消息队列中发送接收消息,假设消息队列已经满了,此时客户端无法向队列中发送消息,阻塞了,而服务器接收完一条消息后,想向消息队列发送 ...

  8. Linux 进程间通讯详解六

    ftok()函数 key_t ftok(const char *pathname, int proj_id); --功能:创建系统建立IPC通讯 (消息队列.信号量和共享内存) 时key值 --参数 ...

  9. Linux 进程间通讯详解三

    msgctl()函数 int msgctl(int msqid, int cmd, struct msqid_ds *buf); --参数 msqid:有msgget函数返回的消息队列标识码 cmd: ...

随机推荐

  1. 洛谷P3567 KUR-Couriers [POI2014] 主席树/莫队

    正解:主席树/莫队 解题报告: 传送门! 这题好像就是个主席树板子题的样子,,,? 毕竟,主席树的最基本的功能就是,维护一段区间内某个数字的个数 但是毕竟是刚get到主席树,然后之前做的一直是第k大, ...

  2. qemu-kvm内存虚拟化1

    2017-04-18 记得很早之前分析过KVM内部内存虚拟化的原理,仅仅知道KVM管理一个个slot并以此为基础转换GPA到HVA,却忽略了qemu端最初内存的申请,而今有时间借助于qemu源码分析下 ...

  3. LeetCode-111.Mininum Depth of Binary Tree

    Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shor ...

  4. Laravel展示产品-CRUD之show

    上一篇讲了Laravel创建产品-CRUD之Create and Store,现在我们来做产品展示模块,用到是show,①首先我们先修改controller,文件是在/app/Http/Control ...

  5. ros 运行rviz时出现 QXcbConnection: XCB error: 148 错误 解决方法

    出现上述问题的原因: 1.由于使用了nvc远程控制下位机: 2.rviz是一个基于opengl开发的图形插件,需要使用理论的屏幕参数(thetis' screen),由于使用了teamviewer会导 ...

  6. 火币网API文档——WebSocket API错误码

    错误信息返回格式 { "id": "id generate by client", "status": "error", ...

  7. 20165236郭金涛 预备作业3 Linux安装及学习

    我在Linux安装过程遇到的问题: 1.“不能为虚拟电脑XX打开一个新任务”: 出现这种情况是电脑没有开启blos,解决方法是:开机进入联想界面的时候,直接按F2可以快速进入选择开启blos. Lin ...

  8. python的开发语言介绍

    -开发语言: 高级语言:python.java.c#.php.GO.ruby.c++    ===>字节码 低级语言:c.汇编   ===>机器码 语言之间的对比: PHP:适用于写网页, ...

  9. model browser 不出现时

    1:当 创建 component 时, 创建完成后,没有出现model browser, 这时需要在model上面添加一个model,然后保存退出,重新进入,就会出现model browser

  10. 【Scrum】-NO.40.EBook.1.Scrum.1.001-【敏捷软件开发:原则、模式与实践】- Scrum

    1.0.0 Summary Tittle:[Scrum]-NO.40.EBook.1.Scrum.1.001-[敏捷软件开发:原则.模式与实践]- Scrum Style:DesignPattern ...