在 shell 中重定向输入和输出

Redirecting input and output in a shell

您好,我一直在用 c 编写 shell,但在尝试重定向时卡住了。在我的程序中重定向标准输出时,标准输入不起作用。

void redirect(node_t* node){
    // mode 0: >$%d mode 1: < mode 2: > mode 3: >>
    int input = 0;
    if(node->redirect.mode == 2){
        input = 1; // >
    } else{
        input = 0; // <
    }
    int pid = 0;
    int *status = 0;
    char * filename = node->redirect.target; // filename
    int fd;
    fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC);
    if((pid = fork()) == 0){
        dup2(fd, input); // STDIN OR STDOUT
        close(fd);
        node_t* node2 = node->redirect.child;
        execvp(node2->command.program, node2->command.argv); // execute program
        printf("failed to execvp\n");
        exit(1);        
    } else {
        wait(status);
    }
}

我是 fork() 的新手,但我的问题是我在这里做错了什么重定向 stdout 有效但 stdin 它没有向给定文件写入任何内容。

如评论中所述,您需要使用不同的打开选项,具体取决于您是打开文件进行输入重定向还是输出重定向。您可以将其放入 if.

int flags;
if(node->redirect.mode == 2){
    input = 1; // >
    flags = O_WRONLY | O_CREAT | O_TRUNC;
} else{
    input = 0; // <
    flags = O_RDONLY;
}
int pid = 0;
int *status = 0;
char * filename = node->redirect.target; // filename
int fd;
fd = open(filename, flags, 0666);

此外,您需要为创建输出文件的情况指定权限模式。始终指定此参数是可以的,当 O_CREAT 不在标志中时它将被忽略。