0

私はCで複数のパイプを実装しようとしています

ls - al | less | wc

パイプラインの作成に問題があります。プロセスを作成し、それらをパイプで接続することになっているループがあります。

for(i=0;i<num_cmds;i++){ 
     create_commands(cmds[i]);
}

私のcreate_commands()関数は次のようになります

void create_commands (char cmd[MAX_CMD_LENGTH]) // Command be processed
{
    int pipeid[2];
    pipe(pipeid);

    if (childpid = fork()) 
    {
        /* this is the parent process */
        dup2(pipeid[1], 1); // dup2() the write end of the pipe to standard output.
        close(pipeid[1]); // close() the write end of the pipe  

        //parse the command
        parse_command(cmd, argvector);

        // execute the command
        execvp(argvector[0], argvector);

        close(1); // close standard output
    }
    else
    {
        /* child process */
        dup2( pipeid[0], 0); // the read end of the pipe to standard input
        close( pipeid[0] ); // close() the read end of the pipe 
    }

}

しかし、これは機能しません。stdinとstdoutが台無しになっています。誰かが私が間違っていることを私に指摘してもらえますか?

前もって感謝します!

4

1 に答える 1

1

popen()関数は、stringコマンドで指定されたコマンドを実行します。呼び出し元のプログラムと実行されたコマンドの間にパイプを作成し、パイプからの読み取りまたはパイプへの書き込みに使用できるストリームへのポインターを返します。

#include <stdio.h>
int main(int argc, char *argv[])
{

    FILE *fp;
    int status;
    int PATH_MAX = 1024;
    char path[PATH_MAX];
    fp = popen("ls -al | less | wc", "r");
    if (fp == NULL)
        /* Handle error */;


     while (fgets(path, PATH_MAX, fp) != NULL)
         printf("%s", path);


     status = pclose(fp);
     if (status == -1) {
    /* Error reported by pclose() */
     } else {
    /* Use macros described under wait() to inspect `status' in order
       to determine success/failure of command executed by popen() */
     }

}

popen()内で呼び出されるプリセット文字列を使用できます。また、argv[]引数を使用して必要に応じてパイプすることもできます。

popen()は、パイプ、FIFO First In First Outストリームを提供し、popenはSTDOUTをプログラムにフィードバックします。

popen()のマニュアルページは次のとおりです。http: //linux.die.net/man/3/popen

于 2013-03-22T22:41:30.303 に答える