2
這裏有一個程序,我試圖讓:重定向標準輸出管道用C
#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();
}
}
我想在孩子重定向孩子的父標準輸出(通過管道)執行EXEC。我認爲這個問題可能與dup2有關,但我之前沒有使用它。
請指定什麼「問題」,而不是隻是傾銷你的代碼,讓我們找出。如果您不知道問題所在,請將錯誤報告添加到您的程序中。 –
不要解決您的問題,但必須爲wait()函數指定int * sts(可以爲NULL)。 –