【发布时间】:2020-11-02 02:44:48
【问题描述】:
我正在编写一个带有两个参数的 porgram - 命令的名称。程序应该将第一个命令的输出重定向到文件“tmp”而不是执行它,而不是将第二个命令的标准输入重定向到“tmp”并执行第二个命令。
#include<unistd.h>
#include<fcntl.h>
#include<wait.h>
#include<stdio.h>
int main(int argc, char** argv){
int fd = open("tmp", O_RDWR |O_TRUNC | O_CREAT, S_IRUSR | S_IWUSR);
int cpid = fork();
if(cpid == 0){
dup2(fd, 1);
execlp(argv[1], "", NULL);
}
wait(NULL);
//If we uncoment this line the program gives correct output
//fd = open("tmp", O_RDWR, S_IRUSR | S_IWUSR);
dup2(fd, 0);
execlp(argv[2], "", NULL);
}
但是,当我像 ./main ls wc 这样运行程序时,而不是
5 5 50
我得到输出 0 0 0 这意味着 wc 命令从标准输入读取 0 个字节。
但是,如果我改为在同一个文件“tmp”上重新创建文件描述符,程序会给出正确的输出。如何解释这种行为?
【问题讨论】:
标签: c unix posix file-descriptor dup