0

argv 配列で指定される特定のファイルで stdout と stdin をリダイレクトしたいと考えています。

たとえば、次のようなコマンドを入力すると - ./shell ls > test

「テスト」ファイルにリダイレクトする必要があります。コードを記述せずにそのファイルに自動的にリダイレクトするため、少し混乱しています。 、標準入力をリダイレクトする必要があります。argv[argc-1] と argv[argc-2] を使用してファイル名と ">" または "<" 記号を見つけようとしましたが、後で ">" とファイル名を使用すると、出力が印刷されるようです (その名前と記号を取得する代わりに、そのファイルで ">" "<" の前の引数を歌います)。

基本的には、execvp() と fork() を使用してシェル コマンドを作成しています。

これが私のコードです。静的ファイルでstdoutをリダイレクトできます。

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

    }
    }
4

2 に答える 2

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>.

stdout をこのファイルにリダイレクトするとします。

dup2(fd,1);//dup2(fd,STDOUT_FILENO)
printf("%s",buff); //this will write it to the file.
于 2015-03-31T01:48:20.180 に答える
0

stdio リダイレクトは、起動されたプログラムではなく、シェルによって処理されます。関連する syscall はpipeopenおよびdup2であり、2 つのうち後者は、読み取りまたは書き込み対象のパイプまたはファイルに stdio ファイル記述子をリダイレクトするために使用されます。

于 2015-03-31T01:47:08.157 に答える