5

これが私が作ろうとしているプログラムです:

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>



int main(int argc, char* argv[])
{
    char* arguments[] = {"superabundantes.py", NULL};

    int my_pipe[2];
    if(pipe(my_pipe) == -1)
    {
        fprintf(stderr, "Error creating pipe\n");
    }

    pid_t child_id;
    child_id = fork();
    if(child_id == -1)
    {
        fprintf(stderr, "Fork error\n");
    }
    if(child_id == 0) // child process
    {
        close(my_pipe[0]); // child doesn't read
        dup2(my_pipe[1], 1); // redirect stdout

        execvp("cat", arguments);

        fprintf(stderr, "Exec failed\n");
    }
    else
    {
        close(my_pipe[1]); // parent doesn't write

        char reading_buf[1];
        while(read(my_pipe[0], reading_buf, 1) > 0)
        {
            write(1, reading_buf, 1); // 1 -> stdout
        }
        close(my_pipe[0]);
        wait();
    }
}

子のstdoutを(パイプを介して)親にリダイレクトする子でexecを実行したいと思います。問題はdup2に関連している可能性があると思いますが、これまで使用したことはありません。

4

2 に答える 2

3

execを呼び出すときに指定する必要があります。argv[0]したがって、引数は次のようになります。

char* arguments[] = {"cat", "superabundantes.py", NULL};
于 2012-05-22T11:48:37.610 に答える
-2
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>



int main(int argc, char* argv[])
{
    //char* arguments[] = {"cat","tricky.txt", NULL};
    char* arguments[] = {"./son1", NULL};
    int my_pipe[2];
    if(pipe(my_pipe) == -1)
    {
       fprintf(stderr, "Error creating pipe\n");
    }

    pid_t child_id;
    child_id = fork();
    if(child_id == -1)
    {
        fprintf(stderr, "Fork error\n");
    }
    if(child_id == 0) // child process
    {
        close(my_pipe[0]); // child doesn't read
        dup2(my_pipe[1], 1); // redirect stdout

        execvp(arguments[0], arguments);

        fprintf(stderr, "Exec failed\n");
    }
    else
    {
        close(my_pipe[1]); // parent doesn't write

        char reading_buf[1];

        while(read(my_pipe[0], reading_buf, 1) > 0)
        {
           write(1, reading_buf, 1); // 1 -> stdout
        }

        close(my_pipe[0]);
        wait();
   }

}

/ * ./son1がson1のprintf()を返す場合、親のwrite(1 ..)によって出力されますson1がデッドループの場合、son1のprintf()は親のwrite(1 ..)によって出力されません

void main()
{
    printf( "***** son run *****\n\r" );
    return;
    while(1);
}

何か案が?
* /

于 2019-08-21T22:34:13.383 に答える