简体   繁体   English

在外壳中重定向输入和输出

[英]Redirecting input and output in a shell

Hi I've been programming a shell in c and I got stuck while trying to redirect. 嗨,我一直在用c编写shell,尝试重定向时被卡住了。 While redirecting the stdout in my program works the stdin doesn't. 在我的程序中重定向标准输出时,标准输入不起作用。

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);
    }
}

I'm new to the fork() but my question is what am I doing wrong here that redirecting stdout works but stdin it writes nothing to the given file. 我是fork()新手,但是我的问题是,在这里重定向stdout可以正常工作,但stdin却没有将任何内容写入给定文件,这是我做错了什么。

As mentioned in the comments, you need to use different open options depending on whether you're opening the file for input or output redirection. 如注释中所述,您需要使用不同的打开选项,具体取决于您是打开文件进行输入重定向还是输出重定向。 You can put this into your if . 您可以将其放入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);

Also, you need to specify the permission modes for the case where the output file is created. 另外,您需要为创建输出文件的情况指定权限模式。 It's OK to specify this argument all the time, it will be ignored when O_CREAT isn't in the flags. 可以一直指定此参数,当O_CREAT不在标志中时,它将被忽略。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM