无名管道通信编写程序实现命令cat功能linuxC语言
时间: 2023-10-07 22:10:39 浏览: 170
下面是一个实现命令cat功能的Linux C语言程序,使用无名管道进行进程间通信:
```c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#define MAX_BUF_SIZE 1024
int main(int argc, char *argv[]) {
int pipe_fd[2]; // 管道文件描述符
char buf[MAX_BUF_SIZE]; // 缓冲区
int n;
if (argc < 2) {
printf("Usage: %s <filename>\n", argv[0]);
exit(EXIT_FAILURE);
}
if (pipe(pipe_fd) == -1) { // 创建管道
perror("pipe");
exit(EXIT_FAILURE);
}
pid_t pid = fork(); // 创建子进程
if (pid == -1) { // fork出错
perror("fork");
exit(EXIT_FAILURE);
} else if (pid == 0) { // 子进程
close(pipe_fd[1]); // 关闭写端
dup2(pipe_fd[0], STDIN_FILENO); // 将管道的读端重定向到标准输入
execlp("cat", "cat", NULL); // 执行cat命令
perror("exec");
exit(EXIT_FAILURE);
} else { // 父进程
close(pipe_fd[0]); // 关闭读端
FILE *fp = fopen(argv[1], "r"); // 打开文件
if (fp == NULL) {
perror("fopen");
exit(EXIT_FAILURE);
}
while (fgets(buf, MAX_BUF_SIZE, fp) != NULL) { // 从文件中读取内容
n = strlen(buf);
if (write(pipe_fd[1], buf, n) != n) { // 写入管道
perror("write");
exit(EXIT_FAILURE);
}
}
close(pipe_fd[1]); // 关闭写端
fclose(fp); // 关闭文件
wait(NULL); // 等待子进程结束
exit(EXIT_SUCCESS);
}
return 0;
}
```
使用方法:
```
$ gcc -o mycat mycat.c
$ ./mycat <filename>
```
其中`<filename>`是要读取的文件名。执行后会将文件内容输出到终端。
阅读全文
相关推荐

















