ImageMagick - Eclipse - c++

I am writing a small program using ImageMagick in Eclipse IDE.
My program compiles and runs fine but every call of display() (method which saws an image in a pop up window) has no effect. Through command line the same calls work fine so I assume that something is going wrong with Eclipse. I appreciate any help in advance.

The Magick::Image::display method is expecting DISPLAY variable to be defined in the run-time environment. In Eclipse, under run/debug configuration, you should be able to set the environment value to whatever your X11 window manager's hostname. You can discover this value by echo-ing it out in command line.
#!/bin/sh
echo $DISPLAY
For your application, it may be wise to add error handling, or a user configuration option.
#include <cstdlib>
// ...
const char * env_display = getenv("DISPLAY");
if ( env_display == NULL ) {
// Error, or attempt to recover
}
You can also set the X11's hostname within the image object with Magick::Image::x11Display.

Related

Running the command line dot program from a Qt application generates no output, what is wrong?

I have an app that generates a dependencies.dot file which I then want to convert to an SVG image.
When I do that from a simple application like so:
int main(int argc, char * argv[])
{
system("dot -Tsvg ../BUILD/dependencies.dot > ../BUILD/dependencies.svg");
return 0;
}
It works great. The SVG image is present and working.
When I instead run it from my Qt application, the SVG file is created (by the shell), but it remains empty.
Any idea what could prevent dot from outputting data to its stdout?
Just in case, I also tried a cat to send the input through stdin instead of a filename:
system("cat ../BUILD/dependencies.dot | dot -Tsvg > ../BUILD/dependencies.svg");
And that didn't make any differences.
Also using the full path (/usr/bin/dot) did not help either.
Another test, I tried to use popen() and the first fread() immediately returns 0 (i.e. the mark of EOF).
It may not be Qt, but something is interacting with dot's ability to do anything. Any pointers on why that is would be wonderful.
Maybe an important note? I start my app. from a console, so stdin, stdout and stderr should all work as expected. I actually can see debug logs appearing there and other apps seem to work just as expected (i.e. My Qt app. can successfully run make, for example).
Here is an example of the resulting SVG (when I don't run it from within my Qt app):
For reference, the source code can be found on github. This is part of the snapbuilder. A tool that I use to run a build on launchpad. It's still incomplete, but it's getting there.
https://github.com/m2osw/snapcpp/tree/master/snapbuilder
The specific function to look for: project::generate_svg().
I still have no clue what side effect Qt has on system() that the dot command would fail. However, if using my own fork() + execve(), then it works.
I wanted a new process class for my environment, so I implemented that. This newer version is using FIFOs or directly opening closing files that it passes to the process.
...
// write the script in `std::stringstream dot` then:
//
std::string script(dot.str());
g_dot_process = std::make_shared<cppprocess::process>("dependencies");
g_dot_process->set_command("/usr/bin/dot");
g_dot_process->add_argument("-Tsvg");
g_dot_process->add_input(cppprocess::buffer_t(script.data(),
script.data() + script.length()));
g_dot_process->set_capture_output();
g_dot_process->set_output_capture_done(output_captured);
g_dot_process->start(); // TODO: check return value for errors
...
// and in output_captured()
//
void snap_builder::svg_ready(std::string const & svg)
{
std::string const svg_filename(...);
{
std::ofstream out;
out.open(svg_filename);
if(!out.is_open())
{
std::cerr << "error: \n";
return;
}
out.write(svg.c_str(), svg.size());
}
dependency_tree->load(QString::fromUtf8(svg_filename.c_str()));
}
Now the dot file is generated and displayed as expected.
This is rather strange since most everything else I've done with a simple system() call works as expected. There must be something about stdin or stdout that makes dot not do its work.

set proxy configuration in c++ code

I have a raspberry running Yocto.
I'm making a code to setup de proxy configuration of the OS connection.
An example of the conde that I'm using is the following
int main(void)
{
system("unset http_proxy");
command = "export http_proxy=\"http://hostname.com\"";
system(command.c_str());
}
The solution on code is not working, however, if I input in a terminal the same command, it works.
What can be the problem?
What can be the problem?
system() creates a sub-process. So changing the http_proxyenvironment variable with a system call doesn't affect the calling process.
You may try to change the environment variable using setenv(), and then fork() and continue in the child process to do whatever you need with the new proxy settings.

Trying to display a text through CMD with C++ and I am presented with a error [duplicate]

This is a probably an embarasing question as no doubt the answer is blindingly obvious.
I've used Visual Studio for years, but this is the first time I've done any 'Console Application' development.
When I run my application the console window pops up, the program output appears and then the window closes as the application exits.
Is there a way to either keep it open until I have checked the output, or view the results after the window has closed?
If you run without debugging (Ctrl+F5) then by default it prompts your to press return to close the window. If you want to use the debugger, you should put a breakpoint on the last line.
Right click on your project
Properties > Configuration Properties > Linker > System
Select Console (/SUBSYSTEM:CONSOLE) in SubSystem option or you can just type Console in the text field!
Now try it...it should work
Starting from Visual Studio 2017 (15.9.4) there is an option:
Tools->Options->Debugging->Automatically close the console
The corresponding fragment from the Visual Studio documentation:
Automatically close the console when debugging stops:
Tells Visual Studio to close the console at the end of a debugging session.
Here is a way for C/C++:
#include <stdlib.h>
#ifdef _WIN32
#define WINPAUSE system("pause")
#endif
Put this at the top of your program, and IF it is on a Windows system (#ifdef _WIN32), then it will create a macro called WINPAUSE. Whenever you want your program to pause, call WINPAUSE; and it will pause the program, using the DOS command. For other systems like Unix/Linux, the console should not quit on program exit anyway.
Goto Debug Menu->Press StartWithoutDebugging
If you're using .NET, put Console.ReadLine() before the end of the program.
It will wait for <ENTER>.
try to call getchar() right before main() returns.
(/SUBSYSTEM:CONSOLE) did not worked for my vs2013 (I already had it).
"run without debugging" is not an options, since I do not want to switch between debugging and seeing output.
I ended with
int main() {
...
#if _DEBUG
LOG_INFO("end, press key to close");
getchar();
#endif // _DEBUG
return 0;
}
Solution used in qtcreator pre 2.6. Now while qt is growing, vs is going other way. As I remember, in vs2008 we did not need such tricks.
just put as your last line of code:
system("pause");
Here's a solution that (1) doesn't require any code changes or breakpoints, and (2) pauses after program termination so that you can see everything that was printed. It will pause after either F5 or Ctrl+F5. The major downside is that on VS2013 Express (as tested), it doesn't load symbols, so debugging is very restricted.
Create a batch file. I called mine runthenpause.bat, with the following contents:
%1 %2 %3 %4 %5 %6 %7 %8 %9
pause
The first line will run whatever command you provide and up to eight arguments. The second line will... pause.
Open the project properties | Configuration properties | Debugging.
Change "Command Arguments" to $(TargetPath) (or whatever is in "Command").
Change "Command" to the full path to runthenpause.bat.
Hit OK.
Now, when you run, runthenpause.bat will launch your application, and after your application has terminated, will pause for you to see the console output.
I will post an update if I figure out how to get the symbols loaded. I tried /Z7 per this but without success.
add “| pause” in command arguments box under debugging section at project properties.
You could run your executable from a command prompt. This way you could see all the output. Or, you could do something like this:
int a = 0;
scanf("%d",&a);
return YOUR_MAIN_CODE;
and this way the window would not close until you enter data for the a variable.
Just press CNTRL + F5 to open it in an external command line window (Visual Studio does not have control over it).
If this doesn't work then add the following to the end of your code:
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
This wait for you to press a key to close the terminal window once the code has reached the end.
If you want to do this in multiple places, put the above code in a method (e.g. private void Pause()) and call Pause() whenever a program reaches a possible end.
A somewhat better solution:
atexit([] { system("PAUSE"); });
at the beginning of your program.
Pros:
can use std::exit()
can have multiple returns from main
you can run your program under the debugger
IDE independent (+ OS independent if you use the cin.sync(); cin.ignore(); trick instead of system("pause");)
Cons:
have to modify code
won't pause on std::terminate()
will still happen in your program outside of the IDE/debugger session; you can prevent this under Windows using:
extern "C" int __stdcall IsDebuggerPresent(void);
int main(int argc, char** argv) {
if (IsDebuggerPresent())
atexit([] {system("PAUSE"); });
...
}
Either use:
cin.get();
or
system("pause");
Make sure to make either of them at the end of main() function and before the return statement.
You can also use this option
#include <conio.h>
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int main() {
.
.
.
getch();
return 0;
}
In my case, i experienced this when i created an Empty C++ project on VS 2017 community edition. You will need to set the Subsystem to "Console (/SUBSYSTEM:CONSOLE)" under Configuration Properties.
Go to "View" then select "Property Manager"
Right click on the project/solution and select "Property". This opens a Test property page
Navigate to the linker then select "System"
Click on "SubSystem" and a drop down appears
Choose "Console (/SUBSYSTEM:CONSOLE)"
Apply and save
The next time you run your code with "CTRL +F5", you should see the output.
Sometimes a simple hack that doesnt alter your setup or code can be:
Set a breakpoint with F9, then execute Debug with F5.
Since running it from VS attaches the VS debugger, you can check for an attached debugger:
if (Debugger.IsAttached)
{
Console.WriteLine("Debugger is attached. Press any key to exit.");
Console.ReadKey();
}
I guess the only caveat is that it'll still pause if you attach any other debugger, but that may even be a wanted behavior.
Use Console.ReadLine() at the end of the program. This will keep the window open until you press the Enter key. See https://learn.microsoft.com/en-us/dotnet/api/system.console.readline for details.
Visual Studio 2015, with imports. Because I hate
when code examples don't give the needed imports.
#include <iostream>;
int main()
{
getchar();
return 0;
}
Currently there is no way to do this with apps running in WSL2. However there are two work-arounds:
The debug window retains the contents of the WSL shell window that closed.
The window remains open if your application returns a non-zero return code, so you could return non-zero in debug builds for example.
It should be added that things have changed since then. On Windows 11 (probably 10, I can't check any more) the new Terminal app that now houses the various console, PowerShell and other sessions has its own settings regarding closing. Look for it in Settings > Defaults > Advanced > Profile termination behavior.
If it's set to close when a program exits with zero, then it will close, even if VS is told otherwise.
Go to Setting>Debug>Un-check close on end.

redhawk module service function usage example crashes

So I am building a redhawk module and trying to just pass data through it as a test. After putting their example of how to work with input and output ports into the serviceFunction() I am able to build the module with no errors (I changed variable names to match my ports). When I put the module on the white board and link it up it's fine but as soon as I start the module it crashes. I added a line to write the incoming stream id to the console and that will hit the console 10 to 20 times before the crash (it correctly writes the id of the signal generator that is providing the signal). If I plot the output port nothing is plotted before the crash (when I say crash I mean that the module just disappears from the white board, the ide is still up and running).
The service function is:
int freqModFrTest_i::serviceFunction()
{
bulkio::InFloatPort::dataTransfer *tmp = dataFloatIn->getPacket(bulkio::Const::BLOCKING);
if (not tmp) { // No data is available
return NOOP;
}
else
{
std::cout<<tmp->streamID<<std::endl;
std::vector<float> outputData;
outputData.resize(tmp->dataBuffer.size());
for (unsigned int i=0; i<tmp->dataBuffer.size(); i++) {
outputData[i] = (float)tmp->dataBuffer[i];
}
// NOTE: You must make at least one valid pushSRI call
if (tmp->sriChanged) {
ComplexOut->pushSRI(tmp->SRI);
}
ComplexOut->pushPacket(outputData, tmp->T, tmp->EOS, tmp->streamID);
delete tmp; // IMPORTANT: MUST RELEASE THE RECEIVED DATA BLOCK
return NORMAL;
}
}
Has anyone had a similar issue or any ideas on what would be causing this?
Additional Info:
Following the sugestion by pwolfram I built a sig generator and this component into a waveform. When launching it from a domain I got the error:
2016-01-14 07:41:50,430 ERROR DCE:aa1a189e-0b5b-4968-9150-5fc3d501dadc{1}:1030 -
Child process 3772 terminated with signal 11
when trying to restart the component (as it just stoped rather then disapering) I get the following error:
Error while executing callable. Caused by org.omg.CORBA.TRANSIENT:
Retries exceeded, couldn't reconnect to 10.62.7.21:56857
Retries exceeded, couldn't reconnect to 10.62.7.21:56857
In REDHAWK 2.0.0 I created a component with the same name (freqModFrTest) and port names (dataFloatIn and ComplexOut) and used your service function verbatim. I did not however get any issues.
Here are a few things to try:
Clean and rebuild the component. The Sandbox (what you referred to as the whiteboard) will run the binary that has been built. It is possible that you've modified the code and have an older version of the binary on disk. Right click on the project and select "clean project". Then right click and select "Build Project" this will make sure that the binary matches your source code.
Run the component in debug mode. If you double click on the SPD file, under the "overview" tab there is "Debug a component in the sandbox". This will launch the component in the chalkboard within a debugging context. You can set breakpoints and walk through the code line by line. If you set no breakpoints though the IDE will stop execution when a fatal error occurs. If there is an issue (like invalid memory access) the IDE will prompt you to enter debug mode and it should point out the line in code where the issue is.
If those options fail, you can enable core dumps and use GDB to see where in the code the issue is occurring. There are lots of tutorials online for GDB but the gist is that before launching the IDE, you'll want to type "ulimit -c unlimited" then from the same terminal, launch the IDE. Now when your component dies, it will produce a core file.
Hopefully one of these gets you going down the right path.

Why does my GStreamer-based C++ application not produce any log output, but gst-tools like "gst-launch" do?

After reading every thread and guide to GStreamer debugging I am still stuck with my problem.
Setting the debug level to GST_DEBUG=*:3 (or any other level) leads to log perfect output when using the gst-tools (e.g. gst-launch-1.0 for testing a certain pipeline), even GST_DEBUG_FILE=filename.txt works.
My problem: My own application that uses GStreamer-stuff a lot does not produce any debug output at all when using the same settings above, any ideas?
Setup: Ubuntu 14-4, Gstreamer 1.0
For anyone who runs into this problem, there is a helpful comment in the code:
The macro is only active if gstreamer is configured with
"--gst-enable-gst-debug" and the environment variable
GST_DEBUG_DUMP_DOT_DIR is set to a basepath (e.g. /tmp).
Therefore, you should set GST_DEBUG_DUMP_DOT_DIR to a specific directory.
Ubuntu : If you want to know the value of GST_DEBUG_DUMP_DOT_DIR:
$ echo $GST_DEBUG_DUMP_DOT_DIR
If the result is empty then you can set it on the terminal using the below line:
$ export GST_DEBUG_DUMP_DOT_DIR=path/to/save/dot/file
and then run your program from the same terminal, or you can set the variable in the /.bashrc file.
second solution
This export can be placed in the main function of our C file:
int main(int argc, char *argv[]) {
putenv("GST_DEBUG_DUMP_DOT_DIR=/tmp");
.
.
.
}
Problem solved: I did start my application with sudo, overwriting my entire environment.