【发布时间】:2017-12-11 10:34:59
【问题描述】:
我正在尝试通过管道使用 bc 获得 char 表达式的答案。 我想首先在 pipe1 中编写表达式,bc 将在 pipe2 中读取和写入答案。为此,我正在更改输入和输出。如果我不使用 char[] 并将表达式放在 write 中,这确实有效:
write(pipe1[1], "20*5\n", sizeof("20*5\n")-1) != sizeof("20*5\n")-1)
但如果我声明一个选项卡,我会不断收到错误消息:
(standard_in) 2: illegal character: ^@
有时是 1 而不是 2
我做错了什么?如果有人能解释一下,谢谢。
代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(void)
{
char resultat[5];
int pipe1[2];
int pipe2[2];
pipe(pipe1);
pipe(pipe2);
int resultat_fork = fork();
if (resultat_fork == -1)
{
exit(EXIT_FAILURE);
}
char* expression = "20*5\n";
if (resultat_fork != 0)
{
//printf("I am the parent\n");
close(pipe1[0]);
close(pipe2[1]);
if (write(pipe1[1], expression, sizeof(expression)) != sizeof(expression))
fprintf(stderr, "write to child failed\n");
int nbytes = read(pipe2[0], resultat, sizeof(resultat));
if (nbytes <= 0)
fprintf(stderr, "read from child failed\n");
else
printf("resultat: %.*s\n", nbytes, resultat);
close(pipe1[1]);
close(pipe2[0]);
}
else
{
printf("I am the child\n");
close(pipe1[1]);
close(pipe2[0]);
dup2(pipe1[0], 0);
dup2(pipe2[1], 1);
close(pipe1[0]); /* More closes! */
close(pipe2[1]); /* More closes! */
execlp("bc", "bc", NULL);
fprintf(stderr, "Failed to execute bc\n");
exit(EXIT_FAILURE);
}
return 0;
}
【问题讨论】:
-
变量
expression是一个指针,而不是一个数组。使用strlen()而不是sizeof。 (我确实在我之前对这个问题的前一个变体的回答的评论中提到了使用strlen()。) -
好吧,请接受我的道歉,我当时真的没有明白。
-
已接受道歉——很难在评论的碎屑中发现有用的信息块(无论是在回答中还是回答后)。