【问题标题】:Pipe between 2 child processes UNIX C2 个子进程 UNIX C 之间的管道
【发布时间】:2011-10-11 11:22:05
【问题描述】:

我在 2 个子进程之间创建了一个管道。一个输出到管道,另一个从管道输入。我能够解析执行命令(或 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
}
}

【问题讨论】:

  • getline() 函数从何而来?如果它是来自 GCC 的,则应该使用动态分配的缓冲区。

标签: c parsing shell unix pipe


【解决方案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(以上示例取自那里并进行了简化)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多