• 2023.10.03


    完成父子进程的通信,
    父进程发送一句话后,子进程接收打印
    然后子进程发送一句话,父进程接收后打印

    1. #include
    2. int main(int argc, char const *argv[])
    3. {
    4. //创建第一个管道
    5. if(mkfifo("./fifo_1",0664)<0){
    6. if(errno!=17){
    7. perror("mkfifo");
    8. return -1;
    9. }
    10. }
    11. //创建第二个管道
    12. if(mkfifo("./fifo_2",0664)<0){
    13. if(errno!=17){
    14. perror("mkfifo");
    15. return -1;
    16. }
    17. }
    18. pid_t cpid=fork();
    19. if(cpid>0){
    20. //打开
    21. char buf[128]="";
    22. while(1){
    23. //打开第一个管道(写)
    24. int fp1=open("./fifo_1",O_WRONLY);
    25. if(fp1<0){
    26. perror("open");
    27. return -1;
    28. }
    29. bzero(buf,sizeof(buf));
    30. printf("父输入数据为>>>");
    31. fgets(buf,sizeof(buf),stdin);
    32. buf[strlen(buf)-1]='\0';
    33. if(strcmp(buf,"quit")==0){
    34. puts("退出输入");
    35. break;
    36. }
    37. write(fp1,buf,sizeof(buf));
    38. puts("发送成功");
    39. //关闭第一个管道
    40. close(fp1);
    41. //打开第二个管道(读)
    42. int fp2=open("./fifo_2",O_RDONLY);
    43. if(fp2<0){
    44. perror("open");
    45. return -1;
    46. }
    47. bzero(buf,sizeof(buf));
    48. off_t res=read(fp2,buf,sizeof(buf));
    49. printf("父读取数据为>>>>%s\n",buf);
    50. if(0==res){
    51. puts("数据读取完成");
    52. break;
    53. }
    54. //关闭第二个管道
    55. close(fp2);
    56. }
    57. }
    58. if(0==cpid){
    59. //打开
    60. char buf[128]="";
    61. while(1){
    62. //打开第一个管道(读)
    63. int fp1=open("./fifo_1",O_RDONLY);
    64. if(fp1<0){
    65. perror("open");
    66. return -1;
    67. }
    68. bzero(buf,sizeof(buf));
    69. off_t res=read(fp1,buf,sizeof(buf));
    70. printf("子读取数据为>>>>%s\n",buf);
    71. if(0==res){
    72. puts("数据读取完成");
    73. break;
    74. }
    75. //关闭第一个管道
    76. close(fp1);
    77. //打开第二个管道(写)
    78. int fp2=open("./fifo_2",O_WRONLY);
    79. if(fp2<0){
    80. perror("open");
    81. return -1;
    82. }
    83. bzero(buf,sizeof(buf));
    84. printf("子输入数据为>>>");
    85. fgets(buf,sizeof(buf),stdin);
    86. buf[strlen(buf)-1]='\0';
    87. if(strcmp(buf,"quit")==0){
    88. puts("退出输入");
    89. break;
    90. }
    91. write(fp2,buf,sizeof(buf));
    92. puts("发送成功");
    93. //关闭第二个管道
    94. close(fp2);
    95. }
    96. }
    97. return 0;
    98. }

  • 相关阅读:
    多城镇信息发布付费置顶公众号开源版开发
    【微信小程序】uni-app 配置网络请求
    Java EnumMap keySet()方法具有什么功能呢?
    UNet网络模型学习总结
    conda虚拟环境总结与解读
    Java注解-最通俗易懂的讲解
    使用 Fastai 构建食物图像分类器
    基础 | 并发编程 - [线程状态 & 中断]
    【Linux练习生】进程间通信
    leetcode.813 最大平均值和的分组 - 前缀和 + dp
  • 原文地址:https://blog.csdn.net/m0_61834469/article/details/133515532