【问题标题】:How to redirect stdout and stdin in a given file using argv in C如何使用 C 中的 argv 重定向给定文件中的标准输出和标准输入
【发布时间】:2015-06-04 05:32:20
【问题描述】:

我想在 argv 数组中给出的特定文件中重定向标准输出和标准输入。

例如,当我输入类似 - ./shell ls > test 的命令时

它应该被重定向到“测试”文件,现在我有点困惑,因为没有编写任何代码它会自动重定向到该文件,我想手动执行它,其次,当我输入一个命令时 - ./shell ls ”或“”和文件名时,输出打印(该文件中 ">" "

基本上,我正在使用 execvp() 和 fork() 创建一个 shell 命令。

这是我的代码,我可以在静态文件中重定向标准输出。

void call_system(char *argv[],int argc)
    {
    int pid;
    int status=0;
    signal(SIGCHLD, SIG_IGN);
    int background;
    /*two process are created*/
    pid=fork();
    background = 0;

    if(pid<0)
    {
        fprintf(stderr,"unsuccessful fork /n");
         exit(EXIT_SUCCESS);
    }
    else if(pid==0)
    {
        //system(argv[1]);
        /*argument will be executed*/

                freopen("CON","w",stdout);
                    char *bname;
                    char *path2 = strdup(*argv);
                    bname = basename(path2);


                        execvp(bname, argv);
                         fclose (stdout);
    }
    else if(pid>0)
    {
    /*it will wait untill the child process doesn't finish*/
    //waitpid(pid,&status,0);

    wait(&status);

    //int tempid;
    //tempid=waitpid(pid,&status,WNOHANG);
    //while(tempid!= pid);// no blocking wait


    if(!WIFEXITED(status) || WEXITSTATUS(status))
    printf("error");



                         exit(EXIT_SUCCESS);

    }
    }

【问题讨论】:

  • 只用&gt;&lt;以外的东西,比如./myprog -i input.file -o output.file

标签: c linux shell execvp freopen


【解决方案1】:

尝试使用dup()dup2()dup3()

dup() 系统调用创建文件描述符 oldfd 的副本, 为新描述符使用编号最小的未使用描述符。

File *fp=fopen(argv[1],"r");
int fd=fileno(fp);

dup2(fd,0); //dup2(fd,STDIN_FILENO) redirect file stream to input stream
scanf("%s",buff); //reading from file.

同样的输出也可以被重定向。从手册中这些信息可能有用

On program startup, the integer file descriptors associated with the
       streams stdin, stdout, and stderr are 0, 1, and 2, respectively.  The
       preprocessor symbols STDIN_FILENO, STDOUT_FILENO, and STDERR_FILENO
       are defined with these values in <unistd.h>.

假设你想将标准输出重定向到这个文件。

dup2(fd,1);//dup2(fd,STDOUT_FILENO)
printf("%s",buff); //this will write it to the file.

【讨论】:

    【解决方案2】:

    stdio 重定向由 shell 处理,而不是启动的程序。相关的系统调用是pipeopendup2,两者中的后者用于将stdio文件描述符重定向到要读取或写入的管道或文件中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-05-11
      相关资源
      最近更新 更多