加入收藏 | 设为首页 | 会员中心 | 我要投稿 西安站长网 (https://www.029zz.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 建站 > 正文

Linux下的进程间通信:共享存储

发布时间:2019-05-11 11:05:58 所属栏目:建站 来源:Marty Kalin
导读:副标题#e# 学习在 Linux 中进程是如何与其他进程进行同步的。 本篇是 Linux 下进程间通信(IPC)系列的第一篇文章。这个系列将使用 C 语言代码示例来阐明以下 IPC 机制: 共享文件 共享内存(使用信号量) 管道(命名的或非命名的管道) 消息队列 套接字 信

在向文件写入内容后,生产者改变锁结构中的 l_type 域为 unlock 值:

  1. lock.l_type = F_UNLCK;

并调用 fcntl 来执行解锁操作。最后程序关闭了文件并退出。

示例 2. 消费者程序

  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <fcntl.h>
  4. #include <unistd.h>
  5.  
  6. #define FileName "data.dat"
  7.  
  8. void report_and_exit(const char* msg) {
  9. [perror][4](msg);
  10. [exit][5](-1); /* EXIT_FAILURE */
  11. }
  12.  
  13. int main() {
  14. struct flock lock;
  15. lock.l_type = F_WRLCK; /* read/write (exclusive) lock */
  16. lock.l_whence = SEEK_SET; /* base for seek offsets */
  17. lock.l_start = 0; /* 1st byte in file */
  18. lock.l_len = 0; /* 0 here means 'until EOF' */
  19. lock.l_pid = getpid(); /* process id */
  20.  
  21. int fd; /* file descriptor to identify a file within a process */
  22. if ((fd = open(FileName, O_RDONLY)) < 0) /* -1 signals an error */
  23. report_and_exit("open to read failed...");
  24.  
  25. /* If the file is write-locked, we can't continue. */
  26. fcntl(fd, F_GETLK, &lock); /* sets lock.l_type to F_UNLCK if no write lock */
  27. if (lock.l_type != F_UNLCK)
  28. report_and_exit("file is still write locked...");
  29.  
  30. lock.l_type = F_RDLCK; /* prevents any writing during the reading */
  31. if (fcntl(fd, F_SETLK, &lock) < 0)
  32. report_and_exit("can't get a read-only lock...");
  33.  
  34. /* Read the bytes (they happen to be ASCII codes) one at a time. */
  35. int c; /* buffer for read bytes */
  36. while (read(fd, &c, 1) > 0) /* 0 signals EOF */
  37. write(STDOUT_FILENO, &c, 1); /* write one byte to the standard output */
  38.  
  39. /* Release the lock explicitly. */
  40. lock.l_type = F_UNLCK;
  41. if (fcntl(fd, F_SETLK, &lock) < 0)
  42. report_and_exit("explicit unlocking failed...");
  43.  
  44. close(fd);
  45. return 0;
  46. }

(编辑:西安站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读