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!
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
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With