7

Short version:

I'm trying to get something like this to work in c using piping:

echo 3+5 | bc

Longer version:

Following simple instructions on pipes at http://beej.us/guide/bgipc/output/html/multipage/pipes.html, I tried creating something similar to last example on that page. To be precise, I tried to create piping in c using 2 processes. Child process to send his output to parent, and parent using that output for his calculations using bc calculator. I've basically copied the example on previously linked page, made a few simple adjustments to the code, but it's not working.

Here is my code:

#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int main(void)
{
    int pfds[2];
    pipe(pfds);

    if (!fork()) {
        close(1);       /* close normal stdout */
        dup(pfds[1]);   /* make stdout same as pfds[1] */
        close(pfds[0]); /* we don't need this */
        printf("3+3");
        exit(0);
    } else {
        close(0);       /* close normal stdin */
        dup(pfds[0]);   /* make stdin same as pfds[0] */
        close(pfds[1]); /* we don't need this */
        execlp("bc", "bc", NULL);
    }
    return 0;
}

I'm getting (standard_in) 1: syntax error message when running that. I also tried using read/write but result is the same.

What am I doing wrong? Thank you!

4

1 に答える 1

6

bc入力は改行で終了する必要があります。使用する

printf("3+3\n");

そしてそれは魔法のように機能します!ところで、これが問題であることを確認できます

$ printf '3+3' | bc
bc: stdin:1: syntax error: unexpected EOF
$ printf '3+3\n' | bc
6
于 2013-01-05T12:33:25.720 に答える