进程间通信——匿名管道

匿名管道代码实现:

#include <iostream>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string>
using namespace std;
int main()
{
    int fd[2]={0};
    if (pipe(fd) < 0)
    { 
		perror("pipe");
		return 1;
	}
    pid_t pid = fork();
    if(pid<0) 
    perror("fork");
    else if(pid>0)
    {
        close(fd[1]);
        char buff[64];
	    while (1)
        {
		    ssize_t s = read(fd[0], buff, sizeof(buff));
		    if (s > 0)
            {
			    buff[s] = '\0';
			    cout<<"father reads:"<<buff<<endl;
		    }
		    else if (s == 0)
            {
			    perror("already read all");
			    break;
		    }
		    else{
			    perror("read error");
			    break;
		    }
	    }
    }
    else
    {
        close(fd[0]);
        while(1)
        {
            string message;
            cout<<"son says: ";
            cin>>message;
            write(fd[1],message.c_str(),strlen(message.c_str()));
            sleep(1);
        }
        
    }
}

注:

1.匿名管道仅限有亲缘关系的进程间通信。

2.匿名管道写进的数据不会写入磁盘,仅在内存中。

3.匿名管道只能单向通信。

4.写进程一直写而读进程不读,那么会使写进程挂起。

5.读进程一直读而写进程不写,那么会使读进程挂起。

6.写进程写完后关闭。读进程读完后继续执行后续任务不会挂起。

7.读进程关闭,而写进程一直写,那么系统会发送SIGPIPE信号终止进程。

相关推荐

  1. 进程通信——匿名管道

    2024-03-18 03:18:02       37 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-18 03:18:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-18 03:18:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-18 03:18:02       82 阅读
  4. Python语言-面向对象

    2024-03-18 03:18:02       91 阅读

热门阅读

  1. LeetCode--14

    2024-03-18 03:18:02       39 阅读
  2. System Verilog学习笔记(二十一)——断言

    2024-03-18 03:18:02       38 阅读
  3. SpringBoot3框架,入门学习

    2024-03-18 03:18:02       30 阅读
  4. 【每日前端面经】2024-03-17

    2024-03-18 03:18:02       31 阅读
  5. Linux磁盘分区————逻辑卷

    2024-03-18 03:18:02       35 阅读
  6. 什么是大Key问题

    2024-03-18 03:18:02       47 阅读
  7. HarmonyOS系统开发ArkTS基础编程语法

    2024-03-18 03:18:02       42 阅读
  8. 空回滚和业务悬挂

    2024-03-18 03:18:02       45 阅读