linux中管道的作用是什么,Linux-管道(day09)

 2023-10-03 阅读 27 评论 0

摘要:?目錄 一、使用C程序訪問環境變量 二、文件輸入重定向 三、管道 四、信號 ? linux中管道的作用是什么、? 三、管道 管道分為:無名管道和有名管道。 1、無名管道   使用pipe(2)可創建無名管道 #include<unistd.h> linux管道符使用方法、int pipe

?目錄

一、使用C程序訪問環境變量

二、文件輸入重定向

三、管道

四、信號


?

linux中管道的作用是什么、?

三、管道

管道分為:無名管道和有名管道。

1、無名管道

  使用pipe(2)可創建無名管道

#include<unistd.h>

linux管道符使用方法、int pipe(int pipefd[2]);

功能:

  創建可用于進程間通信的單向管道

參數:

  pipefd[2]:

    pipefd[0]:讀端

linux管道命令grep,    pipefd[1]:寫端

返回值:

  成功:0

  錯誤:-1,errno被設置

思路:

  (1)父進程創建管道

powershell 管道。  (2)fork(2)創建子進程

  (3)父進程關閉寫端、子進程關閉讀端

  (4)子進程寫,父進程讀

注意:

  無名管道中需要使用到文件描述符,所以,無名管道應用于具有親緣關系(父子,兄弟)的進程通信

?

linux命令行大全。?

#include<stdio.h>
#inlcude<unistd.h>
#include<sys/typs.h>
#include<sys/wait.h>
#include<string.h>
#include<stdlib.h>
int main(void){pid_t pid;char msg[]="this is a test";char buf[128];int fd[2];//創建子進程pid=fork();//創建管道int r =pipe(fd);if(r==-1){perror("pipe");return 2;}if(pid==-1){perror("fork");return 1;}if(pid==0){close(fd[0]);//關閉讀端write(fd[1],msg,strlen(msg));//寫入管道exit(0);}else{close(fd[1]);int rt=read(fd[0],buf,128);write(1,buf,rt);wait(NULL);}return 0;  
}

?

?2、有名管道

  有名管道的實質是創建一個管道問價你,一個向文件寫數據,一個向文件讀數據。

  創建有名管道可以使用函數mkfifo(3)

#include<sys/types.h>

shell界面、#include<sys/stat.h>

int mkfifo(const char *pathname,mode_t mode);

功能:

  創建一個特殊的FIFO文件,文件名字為pathname,mode指定了文件的權限(mask&~umask)

參數:

  pathname:管道文件的名字

redis 管道。  mode:管道文件的權限

返回值:

  成功:0

  失敗:-1,errno被設置

有名管道通信,下面為進程A的代碼

#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<string.h>
#include<fcntl.h>
#include<unistd.h>
int main(int argc,char *argv){char *msg[]="hello world\n";//創建管道文件int m=mkfifo(argv[1],0664);if(m==-1){perror("mkfifo");return 1;}//打開管道文件int fd=open(argv[1],O_RDWR);  if(fd==-1){perror("open");return 2;}write(fd,msg,strlen(msg)+1 );close(fd);return 0;
}

下面為進程B的代碼

Linux管道命令,?

#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<string.h>
#include<fcntl.h>
#include<unistd.h>
int main(int argc,char *argv){char buf[128];int fd= open(argv[1],O_RDONLY);if(fd==-1){perror("open");return 1;}//從管道文件讀取數據int r = read(fd,buf,128);write(1,buf,r)close(fd);return 0;
}

?

?

轉載于:https://www.cnblogs.com/ptfe/p/11011343.html

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/4/111385.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息