Linux 中用于管道操作的 C 语言程序
接下来,我们将创建一个在 Linux 中用于管道操作的 C 语言程序。在此程序中,我们将从输入流中读取一些文本,然后将其打印到输出屏幕上。
首先,让我们了解 Linux 中管道的基本知识。
管道用于传输数据,可用于过程/命令/程序之间的通信,以便在基于 Linux 或 Unix 的系统中传输两个管道间的标准输出。
需要注意的一件重要事情是管道是单向的,即数据可以从左向右流动或从右向左流动。
在此,我们将创建一个管道来读取用户输入并将其打印到输出屏幕。该实现采用大小为 2 的数组,用于获取输入 arr[0] 和返回输出 arr[1]。
Linux 中用于管道操作的 C 语言程序
示例
#include <errno.h>
#include<string.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <unistd.h>
int main(){
int Pipe[2];
char string[100];
if (pipe(Pipe) == -1){
perror("Filed to create pipe");
exit(1);
}
scanf("%s", string);
write(Pipe[1], string, strlen(string)+1);
printf("\n");
read(Pipe[0], string, 5);
printf("%s", string);
}输出
input: TutorialsPoint TutorialsPoint
广告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP