1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
|
#include <unistd.h>
#include <stdio.h>
#include <cstdlib>
#include <cstring>
#include <signal.h>
int outfd[2];
int infd[2];
void alarmed(int sig)
{
if (sig == SIGALRM)
{
char input[100] = "2^32\n";
write(outfd[1], input, 5);
memset(input, 0, sizeof(input));
read(infd[0], input, sizeof(input)); /* Read from child’s stdout */
printf("%s", input);
fflush(stdout);
alarm(5);
}
}
int main()
{
/* Where the parent is going to write to */
pipe(outfd);
/* From where parent is going to read */
pipe(infd);
if (fork() == 0) // code executed by child.
{
close(STDOUT_FILENO);
close(STDIN_FILENO);
dup2(outfd[0], STDIN_FILENO);
dup2(infd[1], STDOUT_FILENO);
close(outfd[0]);/* Not required for the child */
close(outfd[1]);
close(infd[0]);
close(infd[1]);
char* argv[] = { "/usr/bin/bc", "-q", 0 };
execvp(argv[0], argv);
}
// code executed by parent.
close(outfd[0]); /* These are being used by the child */
close(infd[1]);
signal(SIGALRM, alarmed);
alarm(5);
for (bool done = false; !done; )
{
char input[100] = "";
gets(input);
strcat(input, "\n");
write(outfd[1], input, strlen(input));
done = strcmp(input, "quit\n") == 0;
memset(input, 0, sizeof(input));
read(infd[0], input, sizeof(input)); /* Read from child’s stdout */
printf("%s", input);
fflush(stdout);
}
close(outfd[1]);
close(infd[0]);
}
|