gpt4 book ai didi

在两个程序之间用c语言创建管道

转载 作者:行者123 更新时间:2023-11-30 15:10:23 24 4
gpt4 key购买 nike

我一直致力于在两个程序 reader.c 和 writer.c 之间用 c 语言创建管道。我无法获得管道程序运行的输入。管道程序应该接收一个 int,将其发送到写入器程序,然后写入器程序将其输出传送到读取器程序以获得最终输出。下面是这三个类的代码。我想我已经很接近了,但是任何人都可以帮助我将初始 int 输入 argv[2] 放入 writer 类中,然后放入 reader 类中吗?

管道程序(communicat.c)

int main(int argc, char *argv[])
{
int fd[2];
pid_t childpid;
int result;

if (argc != 2)
{
printf("usage: communicate count\n");
return -1;
}
pipe(fd);

childpid = fork();

if (childpid == -1)
{
printf("Error in fork; program terminated\n");
return -1;
}

if(childpid == 0)
{
close(1);
dup(fd[1]);
execlp("writer", "writer", fd[1],(char *) NULL);
}
else
{
childpid = fork();
}
if( childpid == 0)
{
close(0);
dup(fd[0]);
close(fd[0]);
close(fd[1]);
execlp("reader", "reader", (char *) NULL);
}
else
{
close(fd[0]);
close(fd[1]);
int status;
wait(&status);
}
return(0);
}

阅读器.c

int main()
{
int count; /* number of characters in the line */
int c; /* input read */
count = 0;
while ((c = getchar())!= EOF)
{
putchar(c); count++;
if (count == LINELENGTH)
{
putchar('\n'); count = 0;
}
}
if (count > 0)
putchar('\n');
return 0;
}

作家.c

int main(int argc, char *argv[])
{
int count; /* number of repetitions */
int i; /* loop control variable */

if (argc != 2)
{
printf("usage: writer count\n");
return -1;
}
else count = atoi(argv[1]);

for (i = 0; i < count; i++)
{
printf("Hello");
printf("hello");
}
return 0;
}

最佳答案

更正代码以这样执行编写器:

if(childpid == 0)
{
close(1);
dup(fd[1]);
close(fd[0]);
close(fd[1]);
execlp("writer", "writer", argv[1], (char *) NULL);
}

关于在两个程序之间用c语言创建管道,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36210753/

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