gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:00:29 25 4
gpt4 key购买 nike

我正在两个子进程之间创建一个管道。一个将输出到管道,另一个将从管道输入。我能够解析执行命令所需的命令和参数(或 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com