我正在尝试让程序从初始控制台获取输入。获取参数并将它们发送到子fork,对数据运行bc计算器,然后将完成的值返回给父级。
我希望用户输入echo "11*13" | ./mycalc
得到:143
mycalc.c
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include <sys/wait.h>
int main(int argc, char **argv) {
int p[2];
int r[2];
pipe(p);
pipe(r);
pid_t childId = fork();
if(childId == -1)
{
perror("Failed to fork");
return -1;
}
if ( childId == 0)
{
printf("Child Process Has Run\n");
close(p[1]);
close(r[0]);
dup2(p[0], STDIN_FILENO);
dup2(r[1], STDOUT_FILENO);
execlp("bc", "bc", NULL);
} else {
printf("Parent process has run\n");
close(p[0]);
close(r[1]);
write(p[1], argv[1], strlen(argv[1]));
char data[128];
int len = read(r[0], data, 13);
if (len < 0) {
perror("Error reading from child");
}
printf("The data is %s", data);
}
return 1;
}
当我运行它时,我得到了
Parent process has run
Child Process Has Run
并且光标只是在那里等待输入,但无论我输入什么都没有。
答案 0 :(得分:1)
我遇到的问题是管道没有正确关闭。在确保管道关闭后,我能够继续。