利用无名管道通信编写程序实现命令cat的功能。
时间: 2024-05-07 15:22:58 浏览: 11
以下是利用无名管道通信编写实现命令cat的功能的程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#define BUFFER_SIZE 1024
int main(int argc, char *argv[]) {
int pipe_fd[2];
if (argc != 2) {
fprintf(stderr, "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) {
perror("fork");
exit(EXIT_FAILURE);
} else if (pid == 0) { // child process
close(pipe_fd[1]); // close write end of pipe
dup2(pipe_fd[0], STDIN_FILENO); // redirect stdin from pipe
close(pipe_fd[0]); // close read end of pipe
execlp("cat", "cat", NULL); // execute cat command
perror("execlp");
exit(EXIT_FAILURE);
} else { // parent process
close(pipe_fd[0]); // close read end of pipe
int input_fd = open(argv[1], O_RDONLY);
if (input_fd == -1) {
perror("open");
exit(EXIT_FAILURE);
}
char buffer[BUFFER_SIZE];
ssize_t num_read;
while ((num_read = read(input_fd, buffer, BUFFER_SIZE)) > 0) {
write(pipe_fd[1], buffer, num_read); // write data to pipe
}
close(pipe_fd[1]); // close write end of pipe
close(input_fd); // close input file
}
return 0;
}
```
该程序会创建一个无名管道,然后创建一个子进程。子进程将从管道中读取数据,并使用cat命令将其输出到标准输出。父进程将从命令行参数指定的文件中读取数据,并将其写入管道中。这样,子进程就可以从管道中读取数据,并将其输出到标准输出,就像执行cat命令一样。