What this program is supposed to do is ask user a simple arithmetic question, e.g. 5 + 7 and then check the answer with "bc" (whether it's correct).
I have the following code, but I don't understand how to edit it to to store the result from "5 + 7" into a variable (currently the result goes into STDOUT).
Any help is welcome.
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
int main( int argc, char *argv[], char *env[] )
{
char *expr = "5 + 7\n";
int answer;
printf("%s = ", expr);
scanf("%d", &answer);
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("%s\n", expr);
/***********************/
/* How to store printf()'s output into a variable? */
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;
}
You need to create a second pipe and redirect
stdout
to it in the child process.