我正在尝试通过管道运行expand命令以达到最大值。输入需要来自stdin,输出需要进入stdout。下面的预期输入和输出以及我目前正在经历的。目前它 似乎什么也没写给孩子,我也不知道为什么。如果有人可以帮助,那就更好了。谢谢大家的帮助。
预期的输入和输出:
$ ./ expand
> (x + 2)^ 2
x ^ 2 + 4 * x + 4
或
$ ./展开“(x + 2)^ 2”
x ^ 2 + 4 * x + 4
#当前输入和输出:#
$ ./ expand
> (x + 2)^ 2
>
或
$ ./展开“(x + 2)^ 2”
$
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string>
#include <string.h>
#include <cstdio>
#include <cstdlib>
#include <fcntl.h>
#include <errno.h>
#include <iostream> // cin, cout
#include <signal.h>
using namespace std;
int main(int argc, char* argv[]) {
pid_t pid;
unsigned char c;
int pp[2]; // parent writes to child(1) and parent reads from child (0)
int cp[2]; // child writes to parent (1) and child reads from parent(0)
string disable = "display2d:false$";
string start = "expand(";
string end = ");";
string inp, sent;
char tmp[BUFSIZ+1];
if(pipe(pp) < 0|| pipe(cp) <0 ) {
cerr<<"Pipe Failure" << endl;
exit(1);
}
if((pid = fork()) < 0) {
cerr<<"Fork Failure"<<endl;
exit(2);
}
if(pid == 0) { // child process
close(pp[1]); // unused pipes get closed
close(cp[0]);
dup2(pp[0],STDIN_FILENO); // copy stdin
close(pp[0]);
dup2(cp[1],STDOUT_FILENO); // copy stdout
close(cp[1]); // finish closing so exec doesn't see them
execlp("maxima","maxima", "-q", (char*)0);
exit(EXIT_FAILURE);
}
else {
if(argc == 1) { // parent process
close(pp[0]); // close unused ends of pipes
close(cp[1]);
while(1) {
printf("> ");
getline(cin,inp);
if(inp == "quit") { // if quit, send close command
write(pp[1], "quit();" , strlen("quit();"));
close(pp[1]); //close pipes
close(cp[0]);
}
sent = disable+start+inp+end; // sends "display2d:false$expand(inp);\n
write(pp[1], sent.c_str(), sent.length()+1);
do {
read(cp[0], &c, 1);
write(STDOUT_FILENO, &c, 1);
} while(c != '\n');
close(pp[1]);
waitpid(pid, NULL, 0);
close(cp[0]);
}
}
if(argc > 1) {
close(pp[0]);
close(cp[1]);
for(int i = 1; i < argc; i++) {
strcat(tmp, "expand(");
strcat(tmp, argv[i]);
strcat(tmp, ");");
write(pp[1], tmp, strlen(tmp));
write(pp[1], "\n", 1);
do {
read(cp[0], &c, 1);
write(STDOUT_FILENO, &c, 1);
//fflush(stdout);
} while(c != '\0');
}
write(pp[1], "quit()$\n", strlen("quit()$\n"));
close(pp[1]);
waitpid(pid, NULL, 0);
close(cp[0]);
}
}
return 0;
}