• 23管道


    我们把从一个进程连接到另一个进程的一个数据流称为一个“管道”
    管道是半双工的,数据只能向一个方向流动;需要双方通信时,需要建立起两个管道
    只能用于具有共同祖先的进程(具有亲缘关系的进程)之间进行通信;通常,一个管道由一个进程创建,然后该进程调用fork,此后父、子进程之间就可应用该管道。
     
    pipe:匿名管道
     
    包含头文件<unistd.h>
    功能:创建一无名管道
    原型
    int pipe(int fd[2]);
    参数
    fd:文件描述符数组,其中fd[0]表示读端, fd[1]表示写端
    返回值:成功返回0,失败返回错误代码
    #include <unistd.h>
    #include <sys/stat.h>
    #include <sys/wait.h>
    #include <sys/types.h>
    #include <fcntl.h>
    
    #include <stdlib.h>
    #include <stdio.h>
    #include <errno.h>
    #include <string.h>
    #include <signal.h>
    #include <sys/time.h>
    
    
    #define ERR_EXIT(m) 
    	do 
    	{ 
    		perror(m); 
    		exit(EXIT_FAILURE); 
    	} while(0)
    
    
    int main(int argc, char *argv[])
    {
    	int pipefd[2];
    	if (pipe(pipefd) == -1)
    		ERR_EXIT("pipe error");
    
    	pid_t pid;
    	pid = fork();
    	if (pid == -1)
    		ERR_EXIT("fork error");
    
    	if (pid == 0)    //子进程
    	{
    		close(pipefd[0]);
    		write(pipefd[1], "hello", 5);    //向管道内写
    		close(pipefd[1]);
    		exit(EXIT_SUCCESS);
    	}
    
    	close(pipefd[1]);
    	char buf[10] = {0};
    	read(pipefd[0], buf, 10);  //从管道内读
    	printf("buf=%s
    ", buf);
    	
    	return 0;
    
    }
    

    这就是简单的匿名管道的应用。我们这里先不去研究其他的实现。

  • 相关阅读:
    SpringMVC听课笔记(一:SpringMVC概述)
    IDEA快捷键
    Java学习方法以及eclipse看jdk源码
    SpringMVC参数绑定
    正向代理、反向代理
    代理模式
    面试准备
    一致性哈希
    synchronized的底层探索
    哈夫曼编码
  • 原文地址:https://www.cnblogs.com/DamonBlog/p/4392295.html
Copyright © 2020-2023  润新知