我正在制作简单的 ANSI C 程序,模拟 Unix shell。因此,我使用 fork() 创建子进程,并在子进程内部调用 exec() 来运行给定的(由用户)程序。
我需要做的是将文件内容重定向到标准输入,以便将其发送给用户调用的程序。
Example: cat < file \\user wants run cat and redirect content of that file to it by typing this to my program prompt
我正在尝试这样做:
...child process...
int fd = open(path_to_file, O_RDONLY);
int read_size = 0;
while ((read_size = read(fd, buffer, BUF_SIZE)) != 0) {
write(STDIN_FILENO, buffer, read_size);
}
close(fd);
execlp("cat", ...);
Run Code Online (Sandbox Code Playgroud)
一切都很顺利,文件内容被写入标准输入,但在读取整个文件后,cat 仍在等待输入(我需要告诉 cat,输入结束),但我不知道如何:-(?
有任何想法吗?多谢!!!
在子进程中,在open调用之前execlp通过dup2(2)系统调用将标准输入重定向到您的 'ed 描述符:
dup2(fd, 0);
execlp("cat", ...);
Run Code Online (Sandbox Code Playgroud)
您不需要while父级中的循环,因为cat它将自行从新重定向的描述符中读取。