【发布时间】:2013-12-03 21:14:07
【问题描述】:
我在编写 shell 以正确执行文件 IO 重定向时遇到了一些麻烦。在我的印象中,算法是这样的。
给定一个命令:cat file > newfile
我的 sh 如下:
1) 将命令解析成两部分,cat file 和 newfile
2) fd = open(newfile, O_WRONLY | O_CREAT) // This opens the newfile for write or creates the file if it does not exist.
3)close(0) // close stdout
4) dup(fd) // this should copy the file descriptor for newfile into stdout since stdout is available
从这里开始,我以为我已经完成了所有到 fd 0 的输出(例如 printfs()、write(0, buf, 64) 等)都将进入我的新文件。但是,一旦我这样做,我的程序就会循环错误'fd 0 is not open for READ',这似乎是正确的,因为 0 应该是我未读取的文件。不确定是什么试图从 0 读取。
这个逻辑是正确的还是我只是错过了什么?谢谢
【问题讨论】:
-
除了@nemo 的注释之外,最好明确一点:
dup2(fd, 1),它会先为您关闭 1 处的现有文件描述符。 -
好的,谢谢大家。我完全混淆了标准输出和标准输入
-
使用系统头文件中给出的#defines:STDOUT_FILENO 和 STDIN_FILENO
标签: shell unix sh io-redirection