管道2个子进程UNIX C

时间:2011-10-11 11:22:05

标签: c parsing shell unix pipe

我正在两个子进程之间创建一个管道。一个输出到管道,另一个输入管道。我能够解析执行命令所需的命令和参数(或者自管道以来的2)。但是,我认为我的管道设置不正确:

[...] 
type_prompt(); //Type out prompt to the user
read_command(); //Read the command from the user

pipe(&fd[0]); //Create a pipe
proc1 = fork();

//Child process 1
if (proc1 == 0)
{
close(fd[0]); //process1 doenst need to read from pipe
dup2(fd[1], STD_INPUT);
close(fd[1]);
execvp(parameter[0], parameter); //Execute the process
}

//Create a second child process
else
{
//Child process 2
proc2 = fork();
if (proc2 == 0)
{
close(fd[1]);
dup2(fd[0], STD_OUTPUT);
close(fd[0]);
execvp(parameter2[0], parameter2);
}
//Parent process
else
{
waitpid(-1, &status, 0); //Wait for the child to be done
}
}

1 个答案:

答案 0 :(得分:1)

您应该将指针传递给分配有malloc的缓冲区作为getline的第一个参数,例如:

  int bytes_read;
  int nbytes = 100;
  char *my_string;

  /* These 2 lines are the heart of the program. */
  my_string = (char *) malloc (nbytes + 1);
  bytes_read = getline (&my_string, &nbytes, stdin);

有关详细信息,请参阅http://www.crasseux.com/books/ctutorial/getline.html(上面的示例是从那里获取并减少的。)