【发布时间】:2016-12-06 12:14:27
【问题描述】:
我在这个 C 练习中遇到了问题。 任务是创建两个进程。两者通过两个管道连接,这些管道终止于子节点的标准输入和标准输出。然后将子进程替换为 bc。 然后我应该写一个从父进程到子进程(bc)的术语(例如1 + 2)。
管道正在做他们应该做的事情,但是,bc 似乎不喜欢输入。当我写入管道时, bc 会响应以下多行:
(standard_in) 1: illegal character: ^@
这是我目前的解决方案:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
/*Create two pipes:
One from parent to child (pipe_pc)
and one from child to parent (pipe_cp).
*/
int pipe_pc[2], pipe_cp[2];
int cid;
if (pipe(pipe_pc) == -1 || pipe(pipe_cp) == -1) {
printf("Could not pipe\n");
exit(EXIT_FAILURE);
}
// Create child process
cid = fork();
if (cid == -1) {
printf("Could not fork.\n");
exit(EXIT_FAILURE);
}
// Child process
if (cid == 0) {
// Redirect pipes
close(STDOUT_FILENO);
close(STDIN_FILENO);
close(pipe_pc[1]); // Close writing end
close(pipe_cp[0]); // Close reading end
dup2(pipe_pc[0], STDIN_FILENO); // Take stdin from parent
dup2(pipe_cp[1], STDOUT_FILENO); // Give stdout to parent
int err;
// Replace child with bc
err = execl("/usr/bin/bc", "bc --quiet", (char*) NULL);
printf("%s %d\n", "Could not start bc:", err);
exit(err);
}
// Parent Process
else {
char input[128] = "";
char buffer[128] = "";
printf("%s\n", "Parent process running");
// Copy argv to a single string
for(int i=1; i < argc; i++) {
strcat(input, argv[i]);
}
// Write the input to the child's stdin
write(pipe_pc[1], input, sizeof(input);
// Read the child's stdout
read(pipe_cp[0], buffer, sizeof(buffer));
printf("Result: %s\n", buffer);
return 0;
}
}
非常感谢您的提示和帮助,在此先感谢!
【问题讨论】: