Pipe output to bc calculator
Asked Answered
S

1

9

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!

Sloane answered 5/1, 2013 at 12:19 Comment(2)
One thing that strikes me is that you may have a race hazard here.Deherrera
@OliCharlesworth Where do you see potential for a race? The write() in the child and the read() by bc are synchronized by the kernel IIUC.Avelinaaveline
A
8

You must end the input for bc with a newline. Use

printf("3+3\n");

and it'll magically work! BTW, you can verify that this is the problem with

$ printf '3+3' | bc
bc: stdin:1: syntax error: unexpected EOF
$ printf '3+3\n' | bc
6
Avelinaaveline answered 5/1, 2013 at 12:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.