Will loading a DLL dynamically reconcile its stderr to a main application? If so, then how...? - c++

I'm writing a GUI application, using Qt, which links to a third-party DLL that sometimes sends error messages to stderr. I'd like these error messages to be displayed in a window within my GUI.
I couldn't find an established way to redirect stderr (as opposed to std::cerr) even after much searching, so I wrote the following class myself:
class StdErrRedirect : public QObject
{
Q_OBJECT
public:
// Constructor
StdErrRedirect(QTextEdit *errorLog,
QObject *parent = NULL);
// Destructor
~StdErrRedirect();
private slots:
void fileChanged(const QString &filename);
private:
QFile tmp;
QFileSystemWatcher watcher;
QString tmpFileNameQtFormat;
QString tmpFileNameNativeFormat;
QTextEdit *m_errorLog;
QString oldContent;
};
StdErrRedirect::StdErrRedirect(QTextEdit *errorLog,
QObject *parent)
: QObject(parent)
{
// Store the pointer to the error log window
m_errorLog = errorLog;
// Create a temporary filename: first find the path:
tmpFileNameQtFormat = QDir::tempPath();
// Make sure the closing slash is present:
if (!tmpFileNameQtFormat.endsWith(QChar('/')))
tmpFileNameQtFormat.append(QChar('/'));
// Add the file name itself:
tmpFileNameQtFormat.append("nb_stderrlog");
// Obtain a version of the filename in the operating system's native format:
tmpFileNameNativeFormat = QDir::toNativeSeparators(tmpFileNameQtFormat);
// Set up redirection to this file:
freopen(tmpFileNameNativeFormat.toAscii().constData(), "a+", stderr);
// Initialise the QFileSystemWatcher:
connect(&watcher, SIGNAL(fileChanged(const QString &)),
this, SLOT(fileChanged(const QString &)));
watcher.addPath(tmpFileNameQtFormat);
tmp.setFileName(tmpFileNameQtFormat);
}
StdErrRedirect::~StdErrRedirect()
{
// Ensure the temporary file is properly deleted:
fclose(stderr);
tmp.close();
tmp.open(QIODevice::ReadWrite);
tmp.remove();
}
void StdErrRedirect::fileChanged(const QString &filename)
{
tmp.open(QIODevice::ReadOnly);
QTextStream stream(&tmp);
QString content = stream.readAll();
tmp.close();
// Identify what's new, and just send this to the window:
int newchars = content.size() - oldContent.size();
if (newchars)
{
m_errorLog -> append(content.right(newchars));
oldContent = content;
}
}
If I instantiate this from my main window using:
errorLog = new QTextEdit;
redirector = new StdErrRedirect(errorLog);
... then everything I write to stderr appears in the window.
So far, so good. The problem is that the DLL's output still does not. In a call to a DLL function which emits an error, if I put the code:
if (error != _OK)
{
error.PrintErrorTrace();
fprintf(stderr, "Should have printed an error \r\n");
fflush(stderr);
//fsync(_fileno(stderr)); Linux version
_commit(_fileno(stderr));
return;
}
...then the text "Should have printed an error" appears but the error message itself does not.
Now, I've read somewhere that this is probably because the redirection is being set up after the DLL was loaded at the beginning of the application, and so it's own stderr channel is unaffected. Therefore, I should be able to fix this by loading the DLL dynamically, after setting up the redirection, instead.
Here is my question, then: how do I do this? I can try putting the following code at the beginning of my application:
QLibrary extlib;
extlib.setFileName("libname");
extlib.setLoadHints(QLibrary::ResolveAllSymbolsHint);
extlib.load();
...but on its own it has no effect. I think this is because the linker is still setting the library up to be opened automatically. However, if I remove the DLL from the linker (I'm using VS2008, so I remove extlib.lib from the dependency list) then the application won't compile because the compiler can't find the symbols from the DLL.
So there's obviously something deeply wrong with what I'm trying to do here. Can anybody help?
Thanks,
Stephen.

Does the DLL really write to stderr? Or does it write to GetStdHandle(STD_ERROR_HANDLE) ? The first maps to the second, initially. But with freopen() you merely change the mapping. Anything written to STD_ERROR_HANDLE will still go there.
To redirect everyones error output, you would need SetStdHandle.

There is only one stderr, so my guess is that the problem is not that you need to load the dll dynamically, but somewhere in your redirection code. Your redirection code is written Linux style, where in windows things work differently.
if you could test your application on Linux, It would help to pin point the problem. If it works on Linux, that it is surly the redirection code.
Anyway, you should read some more about redirection and windows, as I don't think that what you are trying to do now will help you.

Related

Directly executing a batch through clicked function in qt

So I'm trying to have my "button" directly execute a Batch file, important here is that I don't want it to show me a dialogue and make me chose the path, which is the problem I'm having right now with the following code
void MainWindow::on_pushButton_clicked()
{
QString filename=QFileDialog::getOpenFileName(
this,
tr("Open File"),
"C://",
"All files (*.*);;Text File (*.txt);;Music file (*.mp3)");
}
I think this is probably really simple, but i can't get it, I'm not even learning c++ at the moment but my boss asked me to create something out of my scope (wants me to create a GUI for a batch file and have them interact) and I thought of this approach, which is just creating a GUI that executes it.
I've looked at this question: asked to execute an external program with Qt
but they don't talk about how the file path can directly be added into the code, or if I should even be using Qprocess and how, and if I can pass it through "clicked" function.
I'm really inexperienced, all of the code above I got with the help of the internet, but I really don't know how to program using c++
so could someone please be kind enough to show me how a file path can be added to the code, assuming it's in C:\Users\name_goes_here\Downloads
I'd really appreciate it :D
I'd recommend using QProcess for anything "execute external program" with Qt.
You could do it like this:
void MainWindow::on_pushButton_clicked()
{
QProcess process;
process.start("C:/Users/name_goes_here/Downloads/yourfile.bat");
process.waitForFinished(); // Assuming that you do want to wait for it to finish before the code execution resumes
}
Note the "/" in the path. Only Windows uses the messed up "\" for path separation, which would require you to write "C:\\Users\\.." in any string in C++ as "\" needs to be escaped.
Luckily, Qt uses "/" as the universal separator and translates it to whatever the OS needs as required. So you should just use "/" whenever working with Qt.
This is from the Qt documentation:
Qt uses "/" as a universal directory separator in the same way that "/" is used as a path separator in URLs. If you always use "/" as a directory separator, Qt will translate your paths to conform to the underlying operating system.
And finally, if you don't know how to code in C++, shouldn't you be learning that first instead of trying to execute batch files from within a library as complex as Qt? Sounds like you're trying to do too many new things at once.
This is fairly simple merging your source and the one you linked:
void MainWindow::on_pushButton_clicked()
{
QProcess::execute(
QString::fromLatin1(
"cmd.exe /c C:\\Users\\name_goes_here\\Downloads\\file.bat"));
}
Notes:
I used QProcess::execute() instead of QProcess::start() to make things even simpler.
To achieve execution of the batch file, I pass it to cmd32.exe as this is the interpreter which is responsible.
As MCVE testQProcessBatch.cc:
// Qt header:
#include <QtWidgets>
void on_pushButton_clicked()
{
#if 0 // WORKS:
QProcess::execute(
QString::fromUtf8("cmd.exe /c C:\\Users\\Scheff\\Downloads\\testBatch.bat"));
#else // WORKS AS WELL:
QProcess::execute(
QString::fromUtf8("C:\\Users\\Scheff\\Downloads\\testBatch.bat"));
#endif // 0
}
int main(int argc, char **argv)
{
qDebug() << "Version:" << QT_VERSION_STR;
// main application
QApplication app(argc, argv);
QMainWindow qWin;
QPushButton qBtn(QString::fromLatin1("Start cmd"));
qWin.setCentralWidget(&qBtn);
qWin.show();
QObject::connect(&qBtn, &QPushButton::clicked,
&on_pushButton_clicked);
// run application
return app.exec();
}
and the test batch file testBatch.bat:
echo "This is testBatch.bat"
pause
Tested with VS2013 on Windows 10:
Thanks for contributing guys!
I tried using the QProcess method but I think I'm too inexperienced when it comes to figuring out problems associated with it (which I did face when using this method). the CMD route is probably good but I also thought it was too difficult and both of these methods didn't work for me.
Here's what I have now (thanks to Detonar and ymoreau) and and it seems to be doing the job, this might not be the most optimal approach, but it worked for me!
I included QDesktopServices and QUrl
void MainWindow::on_pushButton_clicked()
{
QString filename="C:\\Users\\Name_goes_here\\Downloads\\test.bat";(
this);
hide(); //optional
QDesktopServices::openUrl(QUrl("file:///"+filename,QUrl::TolerantMode));
}

qlabel mailto link in Qt 4.8.6

I've followed instructions given on previous questions like this
so now if I put a link to a regular page it opens fine with the default browser. But if I want to open a mailto link from QT QLabel 4.8.6 the link does nothing.
What am I doing wrong?
here is the code:
UpgradeMessageDialog* umd = new UpgradeMessageDialog();
umd->ui->label->setOpenExternalLinks(true);
umd->ui->label->setTextInteractionFlags(Qt::TextBrowserInteraction);
umd->ui->label->setText("<a href='mailto:user#foo.com?subject=Test&body=Just a test'>My link</a>");
umd->exec();
umd->ui->label->connect(umd->ui->label,
SIGNAL(linkActivated(const QString&)), umd,
SLOT(linkOpen(const QString&)));
(this is defined as a public slot in the appropriate h file)
void UpgradeMessageDialog::linkOpen(const QString &link)
{
QDesktopServices::openUrl(QUrl(link));
}
Just to clarify: I have a default mail program set up in my computer, and when I type mailto:a#b.c in the browser that program opens fine.
First, there are two ways to handle link activation in QLabel. You should use one of them, but I see you are trying to use both.
This two ways are:
Call openExternalLinks(true), so that QLabel will automatically open links using QDesktopServices::openUrl() instead of emitting the linkActivated() signal.
Connect to the linkActivated() signal and then manually open link in the connected slot (by calling QDesktopServices::openUrl() for example).
Also you use the exec() function wrong. You should put the exec() call after the connect() call, because exec() is blocking so the signal connection will actually happened after the dialog is closed.
So your code should be like this:
umd->ui->label->setText("<a href='mailto:user#foo.com?subject=Test&body=Just a test'>My link</a>");
connect(umd->ui->label, SIGNAL(linkActivated(QString)), umd, SLOT(linkOpen(QString)));
umd->exec();
or like this:
umd->ui->label->setTextFormat(Qt::RichText);
umd->ui->label->setTextInteractionFlags(Qt::TextBrowserInteraction);
umd->ui->label->setOpenExternalLinks(true);
umd->ui->label->setText("<a href='mailto:user#foo.com?subject=Test&body=Just a test'>My link</a>");
And a little advise: put the label initialization code into the UpgradeMessageDialog constructor.
UpgradeMessageDialog::UpgradeMessageDialog(QDialog* parent) : QDialog(parent)
{
ui->label->setTextFormat(Qt::RichText);
ui->label->setTextInteractionFlags(Qt::TextBrowserInteraction);
ui->label->openExternalLinks(true);
ui->label->setText("<a href='mailto:user#foo.com?subject=Test&body=Just a test'>My link</a>");
}
And then you can use your dialog this way:
QScopedPointer<UpgradeMessageDialog> umd = new UpgradeMessageDialog;
umd->exec();
#include <QUrl>
#include <QDesktopServices>
myLabel = new QLabel(this);
myLabel->setTextFormat(Qt::RichText);
myLabel->setText("Email:href='mailto:serge#essetee.be'>serge#essetee.be</a>");
myLabel->setOpenExternalLinks(true);
Now you just have to click the link and the standard mail client will be launched.

QT Creator Main.cpp MainWindow.cpp

I'm currently working on my project for my Master thesis in Mechatronics/Robotics. The goal of y project is to read in a .stl-File and calculate the path for an industrial robot.
Till now everything worked fine for me, but now my professor wants me to develop a GUI, because till now I was just using the command window and wrote all parameters manual. Now I'm working with Qt Creator and developed a simple GUI for my project.
In this interface I got a RadioButton for ascii files. In order my functions work I have to determine if the user is entering a ascii file or an binary file. But here's my first problem. In the command window I just check the argv[] for the string "-ascii". If the user enters this, a flag is set to false.
if(0 == strcmp(argv[i], "-ascii")) {
isBinaryFormat = false;
}
Now I just want to do the same int the GUI. If the RadioButton is checked flag is set to false. So I wrote the following in the main.cpp file
if(ui->radioButton->isChecked()) {
isBinaryFormat = false;
}
But ui is unknown in the main function. After searching for help on google I just found tutorials writing the code in the mainwindow.cpp file. But how can I send the information form the mainwindow file to my main function in the main.cpp file.
A second question would be, if I use the QFileDialog::getOpenFilename method, how can I hand the file name to my other functions. The idea is, the user selects a file anywhere on his PC, and the program opens the file and processes it. But here I got the same problem. I can brows for a file, but how can I transfer the information from the mainwindow.cpp to my main.cpp.
I'm thankful for any help I get. Very grateful a lonely coder
First of all you don't write UI Code in the main.cpp.
You write it where the MainWindow Class is so in MainWindow.cpp and MainWindow.h.
Then your ui-> will work because it then has access to that namespace.
I don't see why you would have functions in Main.cpp?
Without seeing more code you're not likely to get an answer to that.
If you want to use external functions in your classes either declare the methods in the class directly or create a new file like global_function.h and .cpp which you can include in your class. ( don't forget the header guards )
Also shouldn't that code look like this:
if(!ui->radioButton->isChecked())
{
isBinaryFormat = false;
}
because of:
If the RadioButton is checked flag is set to false.
QString fileName = QFileDialog::getOpenFileName(this, tr("Open File"),
"/home",
tr("Images (*.png *.xpm *.jpg)"));
getOpenFileName( ) will return a string containing the path and filename of the selected file which you can pass to your functions then.
Please read some more about how to use Qt.
It's not just about the files, there's a class, too. Learn about them. Solution is to add a getter to your MainWindow class that will return whether the radioButton is checked:
class MainWindow : public QMainWindow
{
public:
// optionally, move implementation in the source file
bool isBinaryFormatChecked() const
{
return ui->radioButton->isChecked();
}
// other stuff ...
};
And then you can access it in your main like window.isBinaryFormatChecked() orwindow->isBinaryFormatChecked() depending on whether you have a pointer or not. Another way would be to make ui in your MainWindow public, so you could access the whole user interface, but that breaks proper encapsulation.
I think you need to go through a few of the (excellent in my opinion) examples supplied with Qt before attempting to integrate your already working console code.
Essentially you really don't want to do that check in the main.cpp, but if you must you could have it in a public function of the mainwindow and call that from your main.cpp file. But then that doesn't really make sense as you don't want to check whether the appropriate radio button is set until the user inputs something. You're going to have to read up on event based programming.

Display QProcess output in another window

I'm using the QT Creator on Ubuntu.
I have GUI with a mainwindow and another window called "progress".
Upon clicking a button the QProcess starts and executes an rsync command which copies a folder into a specific directory. I created a textbrowser which reads the output from the rsync command. Also clicking the button causes the "progress" window to pop up.
So far so so good, now my problem.
Instead of showing the rsync output in my mainwindow i want it to be in progress.
I've tried several methods to get the QProcess into the progress via connect but that doesn't seem to work.
mainwindow.cpp
void MainWindow::on_pushButton_clicked()
{
if (ui->checkBox->isChecked()
)
m_time ="-t";
QObject parent;
m_myProcess = new QProcess();
connect(m_myProcess, SIGNAL(readyReadStandardOutput()),this, SLOT(printOutput()));
QString program = "/usr/bin/rsync";
arguments << "-r" << m_time << "-v" <<"--progress" <<"-s"
<< m_dir
<< m_dir2;
m_myProcess->start(program, arguments);
}
progress.cpp
void Progress::printOutput()
{
ui->textBrowser->setPlainText(m_myProcess->readAllStandardOutput());
}
I know it's pretty messy iv'e tried alot of things and haven't cleaned the code yet also I'm pretty new to c++.
My goal was to send the QProcess (m_myProcess) to progress via connect but that didn't seem to work.
Can you send commands like readyReadAllStandardOutput via connect to other windows (I don't know the right term )?
Am I doing a mistake or is there just another way to get the output to my progress window ?
m_myProcess is a member of the class MainWindow and you haven't made it visible to the class Progress. That's why you have the compilation error
m_myProcess was not declared in this scope
What you could do:
Redirect standard error of m_myProcess to standard output, such that you also print what is sent to standard error (unless you want to do something else with it). Using
m_myProcess.setProcessChannelMode(QProcess::MergedChannels);
Make the process object available outside MainWindow
QProcess* MainWindow::getProcess()
{
return m_myProcess;
}
Read the process output line by line in Progress. It needs to be saved in a buffer because readAllStandardOutput() only return the data which has been written since the last read.
... // somewhere
connect(window->getProcess(), SIGNAL(readyReadStandardOutput()), this, SLOT(printOutput())
...
void Progress::printOutput(){
//bigbuffer is member
bigbuffer.append(myProcess->readAllStandardOutput();)
ui->textBrowser->setPlainText(bigbuffer);
}

QProcess, Cannot Create Pipe

I am running a QProcess in a timer slot at 1 Hz. The process is designed to evoke a Linux command and parse it's output.
The problem is this: after the program runs for about 20 minutes, I get this error:
QProcessPrivate::createPipe: Cannot create pipe 0x104c0a8: Too many open files
QSocketNotifier: Invalid socket specified
Ideally, this program would run for the entire uptime of the system, which may be days or weeks.
I think I've been careful with process control by reading the examples, but maybe I missed something. I've used examples from the Qt website, and they use the same code that I've written, but those were designed for a single use, not thousands. Here is a minimum example:
class UsageStatistics : public QObject {
Q_OBJECT
public:
UsageStatistics() : process(new QProcess) {
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(getMemoryUsage()));
timer->start(1000); // one second
}
virtual ~UsageStatistics() {}
public slots:
void getMemoryUsage() {
process->start("/usr/bin/free");
if (!process->waitForFinished()) {
// error processing
}
QByteArray result = process->realAll();
// parse result
// edit, I added these
process->closeReadChannel(QProcess::StandardOutput);
process->closeReadChannel(QProcess::StandardError);
process->closeWriteChannel();
process->close();
}
}
I've also tried manually deleting the process pointer at the end of the function, and then new at the beginning. It was worth a try, I suppose.
Free beer for whoever answers this :)
QProcess is derived from QIODevice, so I would say calling close() should close the file handle and solve you problem.
I cannot see the issue, however one thing that concerns me is a possible invocation overlap in getMemoryUsage() where it's invoked before the previous run has finished.
How about restructuring this so that a new QProcess object is used within getMemoryUsage() (on the stack, not new'd), rather than being an instance variable of the top-level class? This would ensure clean-up (with the QProcess object going out-of-scope) and would avoid any possible invocation overlap.
Alternatively, rather than invoking /usr/bin/free as a process and parsing its output, why not read /proc/meminfo directly yourself? This will be much more efficient.
First I had the same situation with you. I got the same results.
I think that QProcess can not handle opened pipes correctly.
Then, instead of QProcess, I have decided to use popen() + QFile().
class UsageStatistics : public QObject {
Q_OBJECT
public:
UsageStatistics(){
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(getMemoryUsage()));
timer->start(1000); // one second
}
virtual ~UsageStatistics() {}
private:
QFile freePipe;
FILE *in;
public slots:
void getMemoryUsage() {
if(!(in = popen("/usr/bin/free", "r"))){
qDebug() << "UsageStatistics::getMemoryUsage() <<" << "Can not execute free command.";
return;
}
freePipe.open(in, QIODevice::ReadOnly);
connect(&freePipe, SIGNAL(readyRead()), this, SLOT(parseResult()) );
// OR waitForReadyRead() and parse here.
}
void parseResult(){
// Parse your stuff
freePipe.close();
pclose(in); // You can also use exit code by diving by 256.
}
}
tl;dr:
This occurs because your application wants to use more resources than allowed by the system-wide resource limitations. You might be able to solve it by using the command specified in [2] if you have a huge application, but it is probably caused by a programming error.
Long:
I just solved a similar problem myself. I use a QThread for the logging of exit codes of QProcesses. The QThread uses curl to connect to a FTP server uploads the log. Since I am testing the software I didn't connect the FTP server and curl_easy_perform apparently waits for a connection. As such, my resource limit was reached and I got this error. After a while my program starts complaining, which was the main indicator to figure out what was going wrong.
[..]
QProcessPrivate::createPipe: Cannot create pipe 0x7fbda8002f28: Too many open files
QProcessPrivate::createPipe: Cannot create pipe 0x7fbdb0003128: Too many open files
QProcessPrivate::createPipe: Cannot create pipe 0x7fbdb4003128: Too many open files
QProcessPrivate::createPipe: Cannot create pipe 0x7fbdb4003128: Too many open files
[...]
curl_easy_perform() failed for curl_easy_perform() failed for disk.log
[...]
I've tested this by connecting the machine to the FTP server after this error transpired. That solved my problem.
Read:
[1] https://linux.die.net/man/3/ulimit
[2] https://ss64.com/bash/ulimit.html
[3] https://bbs.archlinux.org/viewtopic.php?id=234915