我正在编写一个程序,使其行为与标准命令行非常相似。在代码的这一部分中,我创建一个新进程,并尝试执行系统调用。我正在测试重定向标准输入和标准输出的功能。 当我们要同时重定向进出时,在重定向标准输入时会引发错误。仅执行其中之一时,程序会成功重定向stdin和stdout。同时设置两者时,它也可以正确地重定向输出。当我将两者都设置为重定向时,该过程中仍将使用stdin。
void execute(CMD * command) {
pid_t pid = fork();
if (pid == 0) {
fflush(stdin);fflush(stdin);
if (command->infile != NULL && command->outfile != NULL) {
int in = open(command->infile, O_RDONLY); //this is the problem line
dup2(in, fileno(stdin));
int out = open(command->outfile, O_RDWR|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR);
dup2(out, fileno(stdout));
execvp(command->command, command->arguments);
close(in); close(out);
} else if (command->infile != NULL) {
int in = open(command->infile, O_RDONLY);
dup2(in, fileno(stdin));
execvp(command->command, command->arguments);
close(in);
} else if (command->outfile != NULL) {
int out = open(command->outfile, O_RDWR|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR);
dup2(out, fileno(stdout));
execvp(command->command, command->arguments);
close(out);
} else {
execvp(command->command, command->arguments);
}
} else {
wait(NULL);
}
}
我很好奇为什么在更改标准输出时同一命令的行为也有所不同。另外,如果我将“ command-> infile”替换为文件路径文字,例如,请参见下文,它工作正常。
void execute(CMD * command) {
pid_t pid = fork();
if (pid == 0) {
fflush(stdin);fflush(stdin);
if (command->infile != NULL && command->outfile != NULL) {
int in = open(command->infile, O_RDONLY);
dup2(in, fileno(stdin));
int out = open(command->outfile, O_RDWR|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR);
dup2(out, fileno(stdout));
execvp(command->command, command->arguments);
close(in); close(out);
} else if (command->infile != NULL) {
int in = open(command->infile, O_RDONLY);
dup2(in, fileno(stdin));
execvp(command->command, command->arguments);
close(in);
} else if (command->outfile != NULL) {
int out = open(command->outfile, O_RDWR|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR);
dup2(out, fileno(stdout));
execvp(command->command, command->arguments);
close(out);
} else {
execvp(command->command, command->arguments);
}
} else {
wait(NULL);
}
}