2012-03-14 75 views
1

我想写一个Qt GUI应用程序,它可以与我从Qt GUI应用程序处理信息的可执行文件进行通信。Qt通过管道到可执行的Linux的双向通信

我可以理解并已经能够实现一个单向的popen()管道,它允许我只将信息发送到命令行实用程序,但输出只出现在Qt底部的应用程序输出窗口中窗口。

我一直在寻找互联网,我想我必须使用fork()和exec()两个管道。

我的问题是没有人知道这个或一些例子的好教程或任何人都可以看到代码来实现这个。

谢谢。

编辑::

我这里有这个代码,但我在哪里,我应该把这个困惑。如果我插入到我的Qt GUI应用程序中,关闭管道会导致错误。

再编辑::

这是我的Qt GUI按钮单击事件。但是,我收到了很多错误,说关闭的管道部件有问题。

mainwindow.cpp:85: error: no matching function for call to ‘MainWindow::close(int&)’ 

关闭管道部件有什么问题?

void MainWindow::on_pushButton_clicked() 
{ 
    QString stringURL = ui->lineEdit->text(); 

    ui->labelError->clear(); 
    if(stringURL.isEmpty() || stringURL.isNull()) { 
     ui->labelError->setText("You have not entered a URL."); 
     stringURL.clear(); 
     return; 
    } 

    std::string cppString = stringURL.toStdString(); 
    const char* cString = cppString.c_str(); 

    char* output; 

    //These arrays will hold the file id of each end of two pipes 
    int fidOut[2]; 
    int fidIn[2]; 

    //Create two uni-directional pipes 
    int p1 = pipe(fidOut);     //populates the array fidOut with read/write fid 
    int p2 = pipe(fidIn);     //populates the array fidIn with read/write fid 
    if ((p1 == -1) || (p2 == -1)) { 
     printf("Error\n"); 
     return 0; 
    } 

    //To make this more readable - I'm going to copy each fileid 
    //into a semantically more meaningful name 
    int parentRead = fidIn[0]; 
    int parentWrite = fidOut[1]; 
    int childRead = fidOut[0]; 
    int childWrite = fidIn[1]; 

    ////////////////////////// 
    //Fork into two processes/ 
    ////////////////////////// 
    pid_t processId = fork(); 

    //Which process am I? 
    if (processId == 0) { 
     ///////////////////////////////////////////////// 
     //CHILD PROCESS - inherits file id's from parent/ 
     ///////////////////////////////////////////////// 
     close(parentRead);  //Don't need these 
     close(parentWrite);  // 

     //Map stdin and stdout to pipes 
     dup2(childRead, STDIN_FILENO); 
     dup2(childWrite, STDOUT_FILENO); 

     //Exec - turn child into sort (and inherit file id's) 
     execlp("htmlstrip", "htmlstrip", "-n", NULL); 

    } else { 
     ///////////////// 
     //PARENT PROCESS/ 
     ///////////////// 
     close(childRead);  //Don't need this 
     close(childWrite);  // 

     //Write data to child process 
     char strMessage[] = cString; 
     write(parentWrite, strMessage, strlen(strMessage)); 
     close(parentWrite);  //this will send an EOF and prompt sort to run 

     //Read data back from child 
     char charIn; 
     while (read(parentRead, &charIn, 1) > 0) { 
      output = output + (charIn); 
     } 
     close(parentRead);  //This will prompt the child process to quit 
    } 

    return 0; 
} 

回答