c - 2 个子进程之间的管道 UNIX C

标签 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
}
}

最佳答案

您应该将指向使用 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了解更多详细信息(上面的示例取自此处并进行了简化)。

关于c - 2 个子进程之间的管道 UNIX C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7725225/

相关文章:

bash - 如何用awk在末尾添加新行

Bash 长选项/标志 - 怎么做?

c - strn*() 与 str*() 相比有多快?

c - 如何检查 C 中的某些字符

c - TrueType 到 C 数组

xml - 我不想解析 XML 中的某些标签

c - 如何从正在执行可能抛出它的文件的 shell 脚本捕获信号?

c - 尝试掌握 C 字节码...GNU/gcc 是否/可以像 Clang/LLVM 一样生成 C 字节码?

C 检测 popen 子进程中的错误

java - 为什么 ANTLR 没有正确打印 token 集?