利用无名管道通信编写程序实现命令cat的功能。
时间: 2024-01-22 17:21:16 浏览: 22
可以利用无名管道(pipe)来实现命令cat的功能,具体实现如下:
```c
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
int main(int argc, char *argv[]) {
int pipefd[2];
pid_t cpid;
char buf;
// 创建无名管道
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
cpid = fork();
if (cpid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (cpid == 0) { // 子进程
close(pipefd[1]); // 关闭写入端
while (read(pipefd[0], &buf, 1) > 0) { // 从管道中读取数据并输出
printf("%c", buf);
}
close(pipefd[0]);
exit(EXIT_SUCCESS);
} else { // 父进程
close(pipefd[0]); // 关闭读取端
while (read(STDIN_FILENO, &buf, 1) > 0) { // 从标准输入中读取数据并写入管道
write(pipefd[1], &buf, 1);
}
close(pipefd[1]); // 关闭写入端
wait(NULL); // 等待子进程结束
exit(EXIT_SUCCESS);
}
}
```
上述代码中,首先创建了一个无名管道pipefd,然后创建子进程,子进程关闭写入端,从管道中读取数据并输出;父进程关闭读取端,从标准输入中读取数据并写入管道,最后等待子进程结束。
该程序的运行效果和cat命令类似,可以通过命令行参数传入文件名,例如:
```
./pipe_cat text.txt
```
也可以通过标准输入输入文本内容,例如:
```
./pipe_cat
hello world
```
在输入完文本内容后可以按ctrl+d结束输入。