在shell中重定向输出?

时间:2017-04-21 21:45:09

标签: c shell

我编写了一个函数,用于将某些命令的输出重定向到文件。像这样的东西

  

ls> ls.txt

这是输出重定向的函数:

    int redirect_output(char* cmdline, char **output_filename) {
    int i;
    char* args[MAX_ARGS];

   // int nargs = get_args(cmdline, args);

    for(i = 0; args[i] != NULL; i++) {
        // Look for the >
        if(!strcmp(args[i], ">")) {
              // Get the filename
            if(args[i+1] != NULL) {
                *output_filename = args[i+1];
            } else {
                return -1;  //syntax error
            }
            return 1;       //there is an > 
        }
    }
    return 0;   //no redirect
}

该函数成功将某些命令的输出重定向到文件,但由于某种原因导致其他命令停止工作。例如,我的redirect_output程序适用于类似ls的程序,但它不适用于cat ls.txt之类的内容,如果我不调用它适用于任何命令的函数。并且,通过不工作意味着它被卡住了。以下是其他重要功能。

int get_args(char* cmdline, char* args[])
{
    int i = 0;

    /* if no args */
    if((args[0] = strtok(cmdline, "\n\t ")) == NULL)
        return 0;

    while((args[++i] = strtok(NULL, "\n\t ")) != NULL) {
        if(i >= MAX_ARGS) {
            printf("Too many arguments!\n");
            exit(1);
        }
    }
    /* the last one is always NULL */
    return i;
}

void execute(int output, char *outputefile, char* cmdline)
{
    int pid, async;
    char* args[MAX_ARGS];

    int nargs = get_args(cmdline, args);
    if(nargs <= 0) return;

    if(!strcmp(args[0], "quit") || !strcmp(args[0], "exit")) {
        exit(0);
    }

    /* check if async call */
    if(!strcmp(args[nargs-1], "&")) {
        async = 1;
        args[--nargs] = 0;
    }
    else async = 0;

    pid = fork();
    if(pid == 0) { /* child process */
        //if(output)
           // freopen(outputefile, "w+", stdout);
        execvp(args[0], args);
        /* return only when exec fails */
        perror("exec failed");
        exit(-1);
    } else if(pid > 0) { /* parent process */
        if(!async) waitpid(pid, NULL, 0);
        else printf("this is an async call\n");
    } else { /* error occurred */
        perror("fork failed");
        exit(1);
    }
}

这是我的主要内容:

int main (int argc, char* argv [])
{
    char cmdline[BUFSIZ];
    char *output_filename;
    char **args;
    int output;

    for(;;) {
        printf("COP4338$ ");
        if(fgets(cmdline, BUFSIZ, stdin) == NULL) {
            perror("fgets failed");
            exit(1);
        }

         output = redirect_output(cmdline, &output_filename);

        switch(0) {
        case -1:
            printf("Syntax error!\n");
            break;
        case 0:
            break;
        case 1:
            printf("Redirecting output to: %s\n", output_filename);
            break;
        }

        execute (output, output_filename, cmdline);
  }
    return 0;
}

任何帮助将不胜感激!谢谢!

0 个答案:

没有答案