使用未命名管道的IPC

时间:2018-10-06 17:33:38

标签: c++ c++11 unix ipc unistd.h

首先,您好,感谢您的帮助!

我试图通过未命名的管道来理解IPC。具体来说,我将与Maxima进行交流,以扩展从stdin抓取并发送到输入Maxima的输入,然后将该输出发送到stdout。因此,只需从stdin读取输入,将其发送给子级,然后将输出写入stdout。目前,我已将其输出:

  

输入“>(x + 2)^ 2”

     

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

这是正确的,但是输入和输出之间不应存在换行符,并且(%o2)来自Maxima格式的输出,因此也不应存在。

我想我的问题现在涉及两件事:

1)我该如何解决我的输出问题,使之格式化为没有尾随换行符和输出指示符? 2)我可以解决以下代码吗?我能做些什么?为什么? (我的代码尚未完成,因为我想写另一个段)

#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;}

样本输入和输出

  

$。/ expand

     

>(x + 2)^ 2

     

x ^ 2 + 4 * x + 4

当前输出

  

(%o#)x ^ 2 + 4 * x + 4

0 个答案:

没有答案