Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pipe output to bc calculator

Tags:

c

bash

pipe

bc

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!

like image 207
Xitac Avatar asked Jan 05 '13 12:01

Xitac


1 Answers

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
like image 192
Jens Avatar answered Sep 19 '22 20:09

Jens