Reputation: 13
I'm trying to establish a live communication between a QT program and a VS C++ program. However, I can read anything unless I close the writechannel in which I can't write anything anymore. Furthermore, the code I have now reads a continuous stream of output when I write one line to the VS C++ program when it should be waiting for the next input. Is there a way to establish synchronous communication with the two? What is wrong with my current program?
I've read documentation and can't seem to get a clear answer.
My Qt code:
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
process = new QProcess(this);
connect(process, SIGNAL(readyReadStandardOutput()), this, SLOT(readOutput()));
//connect(process, SIGNAL(readyReadStandardError()),this,SLOT(readOutput()));
process->setArguments(args);
process->setProgram("C:\\Users\\chten\\OneDrive\\Desktop\\QProcess\\test\\Debug\\test.exe");
process->start();
process->waitForStarted();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::readOutput() {
ui->input->append(process->readAllStandardOutput());
}
void MainWindow::on_pushButton_2_pressed()
{
process->write("left");
process->waitForBytesWritten();
process->closeWriteChannel();
}
My C++ code:
cout << "waiting for response..." << endl;
string input_line;
//getline(cin, input_line);
//cout << input_line << endl;
while (true) {
getline(cin, input_line);
cout << input_line << endl;
for(int i = 0; i<9999999; i++){}
}
return 0;
Upvotes: 1
Views: 205
Reputation: 12879
I think the problem is that you never write a line to the child process, you just have...
process->write("left");
No newline. In the meantime the child is executing...
getline(cin, input_line);
waiting for the newline delimiter.
The reason closing the write channel appears to work is that it will cause the getline
call in the child to receive an end-of-file condition and return. However, it will also set the eofbit
in the input stream's state causing further calls to getline
to return immediately: hence the "continuous stream of output"
you refer to.
Try changing the implementation of MainWindow::on_pushButton_2_pressed
to...
void MainWindow::on_pushButton_2_pressed ()
{
process->write("left\n");
process->waitForBytesWritten();
}
and change the child's source code to...
std::cout << "waiting for response..." << endl;
std::string input_line;
while (std::getline(std::cin, input_line)) {
std::cout << input_line << std::endl;
for(int i = 0; i<9999999; i++) {
}
}
return 0;
(All untested.)
As an aside, using Qt
functions such as waitFoStarted
, waitForBytesWritten
etc. can be convenient but should be avoided. Far better to connect to and handle the various signals available.
Upvotes: 3