samedi 6 octobre 2018

IPC using unnamed Pipes

First off, Hello and thanks for your help!

I'm trying to get an understanding of IPC with unnamed pipes. Specifically, I'm going to be communicating with Maxima to expand an input that was grabbed from stdin and sent to the input Maxima and then that output is sent to stdout. So simply read input from stdin send it to the child and then write the output to stdout. Currently, I've gotten it to output:

Input ">(x+2)^2"

(%o2) x^2+4x+4

which is correct, but there is a newline between the input and output which shouldn't be there and the (%o2) comes from the Maxima formatted output, so that also should not be there.

I guess my question now comes to two things:

1) How do I fix my output so that it is formatted without the trailing newline and the output indicator? 2) What about the following code can I fix? What can I make better? and Why? (My code is not yet near completion because I have another segment I wish to write)

#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string>
#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;
    int status;
    int count;
    int fpipe[2];
    string start = "display2d:false$expand("; string end = ");"; string inp, sent;
    string quit = "quit();";
    string buffer;

    if(pipe(fpipe)){cerr<<"Pipe Failure" << endl; exit(1);}
    if((pid = fork()) < 0){ cerr<<"Fork Failure"<<endl; exit(2);}
    if(pid == 0){ // child process
        close(0); // close stdin
        dup(fpipe[0]); // copy stdin
        close(fpipe[1]);
        execlp("maxima", "maxima", "-q", (char*)0);
        read(fpipe[0], (void*)buffer.c_str(), buffer.length());
        cout << buffer << "   1" << endl;
        exit(EXIT_FAILURE);

    }
    else{
         if(argc == 1){ // parent process
        //close(fpipe[0]);
        close(1); // close stdout
        //dup(fpipe[1]); // redirect stdout
        while(1){
        cout << ">";
        cin >> buffer;
        if(buffer == "quit"){
            break;
        }
        buffer = start+buffer+end+'\n';
        int dp = write(fpipe[1], buffer.c_str(), buffer.length());
        //cout << buffer << endl;
        waitpid(getpid(), &status, 0);
        }
        }
        else if(argc > 1){ // just do it for # of argc




        }
}
return 0;}

Aucun commentaire:

Enregistrer un commentaire