将输入从文件重定向到exec()

时间:2012-02-28 18:35:28

标签: c input exec fork

我正在制作简单的ANSI C程序,它模拟Unix shell。所以我使用fork()和子进程内部创建子进程我调用exec()来运行给定(由用户)程序。

我需要做的是将文件内容重定向到stdin,因此可以将其发送给用户称为程序。

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", ...);

一切顺利,文件内容被写入stdin,但是在读完整个文件之后,cat还在等待输入(我需要告诉cat,输入结束了),但我无法弄清楚: - (?

有什么想法吗?非常感谢!!!

1 个答案:

答案 0 :(得分:4)

在子流程中,在通过dup2(2)系统调用调用open之前,将标准输入重定向到execlp'ed描述符:

dup2(fd, 0);
execlp("cat", ...);

您不需要父级中的while循环,因为cat将自己从新重定向的描述符中读取。