Raspicam free resources - c++

I'm trying to do basic image capture with the raspicam C++ libraries from http://www.uco.es/investiga/grupos/ava/node/40
The image capture generally works but seems that I can't run the program again once it's ended, or it hangs on grab_retrieve. The system requires a reboot. My guess is that something is not freeing up resources but am not sure how to diagnose that.
How can I get this utility to clean up after itself?
Code is below. Alternative suggestions are also welcome, as I am not tied to this library.
#include <iostream>
#include <fstream>
#include <unistd.h>
#include <stdio.h>
#include "../raspicam-0.1.3/src/raspicam.h"
#include "../raspicam-0.1.3/src/raspicam_still.h"
#include "../raspicam-0.1.3/src/raspicamtypes.h"
using namespace std;
int main ( int argc, char *argv[] ) {
raspicam::RaspiCam_Still still;
still.setEncoding ( raspicam::RASPICAM_ENCODING_JPEG );
int length=still.getImageBufferSize();
unsigned char *data=new unsigned char[length];
cout<<"Capturing image at size " << length <<endl;
if(!still.grab_retrieve(data, length)) {
cerr<<"Error in grab"<<endl;
return -1;
}
still.release();
cout<< "Got it" << endl;
ofstream file ( "picture.jpg",ios::binary );
file.write ( ( char* ) data, length );
delete[] data;
return 0;
}

Related

Is there a function for sleeping a set amount in C++ for windows?

I know there is one in C, Sleep(ms), but is there one for C++? I am trying to return an error, then print to the console, then sleep enough for the user to read it before returning the errorcode. Code in C would be:
#include <stdio.h>
#include <windows.h>
int main (int argc, const char *argv[]) {
char *err = "Have an error!";
printf("Error: %s. Program terminating in 5 seconds...", err);
Sleep(5000);
return 1;
}
You could include <windows.h> and just call the WinApi function Sleep just as you would from C. This is mostly pure C++ :
#include <iostream>
#include <string>
#include <chrono>
#include <thread>
using namespace std;
int main (int argc, const char *argv[]) {
string err = "Have an error!";
cout << "Error: " << err << ". Program terminating in 5 seconds..." << endl;
std::chrono::milliseconds timespan(5000);
std::this_thread::sleep_for(timespan);
return 1;
}

Trying to detect monitor

I'm trying to get the monitor in order to check if is off or not.
Before checking with GetDevicePowerState, I'm trying to retrieve monitor in this way:
#include <cstdlib>
#include <iostream>
#include <windows.h>
#include <winuser.h>
using namespace std;
int main(int argc, char *argv[])
{
POINT* p = new POINT;
p->x=0;
p->y=0;
HMONITOR* monitor = MonitorFromPoint(p,DWORD.MONITOR_DEFAULTTOPRIMARY);
system("PAUSE");
return EXIT_SUCCESS;
}
But it continually gives me:
main.cpp `MonitorFromPoint' undeclared (first use this function)
Where have I gone wrong?
Your code has a number of problems, but none of them should cause the error message you're seeing. Here's code with some corrections, and a little more added to show at least some kind of result from the test:
#include <iostream>
#include <windows.h>
int main(int argc, char *argv[])
{
POINT p{ 0, 0 };
HMONITOR monitor = MonitorFromPoint(p, MONITOR_DEFAULTTONULL);
if (monitor == NULL)
std::cout << "No monitor found for point (0, 0)\n";
else {
MONITORINFOEX info;
info.cbSize = sizeof(info);
GetMonitorInfo(monitor, &info);
std::cout << "Monitor: " << info.szDevice << "\n";
}
}
I've tested this with both VC++ 2013 and MinGW 4.8.1, and in both cases it's compiled and run without any problems, producing:
Monitor: \\.\DISPLAY1
...as its output in both cases.

C++ fstream multiple input files

I am writing a simple program to take in two files. The terminal command line looks like this.
./fileIO foo.code foo.encode
When it runs, the second file is not read in. When I enter
./fileIO foo.code foo.code
it works. I can't seem to figure out why the second one is not opening. Any ideas? Thanks!
#include <fstream>
#include <iostream>
#include <queue>
#include <iomanip>
#include <map>
#include <string>
#include <cassert>
using namespace std;
int main( int argc, char *argv[] )
{
// convert the C-style command line parameter to a C++-style string,
// so that we can do concatenation on it
assert( argc == 3 );
const string code = argv[1];
const string encode = argv[2];
string firstTextFile = code;
string secondTextFile = encode;
//manipulate the first infile
ifstream firstFile( firstTextFile.c_str(), ios::in );
if( !firstFile )
{
cerr << "Cannot open text file for input" << endl;
return 1;
}
string lineIn;
string codeSubstring;
string hexSubstring;
while( getline( firstFile, lineIn ) )
{
hexSubstring = lineIn.substr(0, 2);
codeSubstring = lineIn.substr(4, lineIn.length() );
cout << hexSubstring << ", " << codeSubstring << endl;
}
//manipulate the second infile
ifstream secondFile( secondTextFile.c_str(), ios::in );
if( !secondFile )
{
cerr << "Cannot open text file for input" << endl;
return 1;
}
char characterIn;
while( secondFile.get( characterIn ) )
{
cout << characterIn << endl;
}
return 0;
}
One thing you might want to try is adding the close() call as is standard procedure after you're done using files. Sometimes issues arise with re-opening files if they were not closed properly in a previous run.
firstFile.close();
secondFile.close();
Also, you may try restarting the computer if there is some lingering file handle that hasn't been released.

output list of files from popen to ifstream.open

Basically I need to open and read a list of files I get from another command.
For each line of output of popen
open a file usen ifstream.open
it compiles and if I put the file name directly it works fine, but it doesn't do anything when using popen output. I've seen questions like this but none of this particular way of giving filenames.
here's the code:
#include <iostream>
#include <sqlite3.h>
#include <stdio.h>
#include <fstream>
using namespace std;
int main () {
ifstream singlefile;
FILE *filelist;
char filename[512];
string progline;
if(!(filelist = popen("find `pwd` -name \"*.js\"", "r"))){
return 1;
}
while( fgets(filename, sizeof(filename), filelist)!=NULL)
{
cout << filename;
singlefile.open(filename, ifstream::in);
while ( singlefile.good() )
{
getline (singlefile,progline);
cout << progline << endl;
}
singlefile.close();
}
pclose(filelist);
return 0;
}
next step would be not open each file inside the loop but to store the file list and then open each file.
Thanks
fgets keeps the trailing newline, resulting in a filename of a non-existing file. Also the stream state is only updated after reading. If I replace the while body with the following code, it works for me:
cout << filename;
size_t len = strlen(filename);
// chop off trailing newline
if (len > 1 && filename[len - 1] == '\n') filename[len - 1] = 0;
singlefile.open(filename, ifstream::in);
while ( getline(singlefile, progline) )
{
cout << progline << endl;
}
singlefile.close();
If you actually want to iterate through a list of files, I'd use Boost.Filesystem, which has a nice C++ interface, works for all filenames (even for those with newlines), and is platform-independent.
If this actually is only an example and your actual command is not find, there is still some room for simplification. Here is a suggestion that uses Boost.Iostreams to get rid of most of the C function calls (it would be great to have a device source reading from a process's standard output, but Boost.Iostreams lacks that):
#include <cstdio>
#include <iostream>
#include <fstream>
#include <stdexcept>
#include <string>
#include <stdio.h>
#include <boost/noncopyable.hpp>
#include <boost/iostreams/stream.hpp>
#include <boost/iostreams/device/file_descriptor.hpp>
using namespace std;
namespace io = boost::iostreams;
class Popen: private boost::noncopyable {
public:
explicit Popen(const char* command):
m_stream(popen(command, "r")) {
if (!m_stream) throw runtime_error("popen failed");
}
~Popen() {
pclose(m_stream);
}
FILE* stream() const {
return m_stream;
}
private:
FILE* m_stream;
};
int main() {
Popen pipe_wrapper("find `pwd` -name \"*.cpp\"");
io::file_descriptor_source pipe_device(fileno(pipe_wrapper.stream()), io::never_close_handle);
io::stream<io::file_descriptor_source> pipe_stream(pipe_device, 0x1000, 0x1000);
string filename;
while (getline(pipe_stream, filename)) {
cout << filename << endl;
ifstream file_stream(filename.c_str(), ifstream::in);
string progline;
while (getline(file_stream, progline)) {
cout << progline << endl;
}
}
}

C++ dup2 and execl

I am working on an assignment and I need to create pipes so that other programs handle different functions. I am able to pipe through the command line no problem, thats easy. However using dup2 and execl have been tricky for me. At one point I was able to get output from one part of my program but it wasn't reading anything in from another part.
here is what i have:
pipeline.cpp
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <cstdlib>
#include <iostream>
#include <cctype>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include<iostream>
#include<cstdlib>
#include<unistd.h>
#include<iomanip>
#include <sys/wait.h>
using namespace std;
int main(int argc, char *argv[])
{
int number = atoi(argv[1]);
int x2ypipe[2];
pipe(x2ypipe);
if(x2ypipe==0){
cout<<"ERROR:"<<errno<<endl;
}
pid_t xchild =fork();
if(xchild==0){
dup2(x2ypipe[1],STDOUT_FILENO);
close(x2ypipe[0]);
close(x2ypipe[1]);
execl("./part1.cpp","part1.cpp", (char *)NULL);
}
pid_t ychild =fork();
if(ychild==0){
dup2(x2ypipe[0],STDIN_FILENO);
close(x2ypipe[0]);
close(x2ypipe[1]);
execl("./part2.cpp", "part2.cpp", (char *)NULL);
}
close(x2ypipe[0]);
close(x2ypipe[1]);
wait(NULL);
wait(NULL);
part1.cpp
#include<iostream>
#include<cstdlib>
#include<unistd.h>
#include<iomanip>
using namespace std;
int main(int argc, char *argv[])
{
int number = atoi(argv[1]);
for (int k = 1; k <= 9; k++)
{
cout << k << " " << flush;
sleep(1);
}
return 0;
}
part2.cpp
#include <iostream>
#include <cstdlib>
#include <unistd.h>
#include <iomanip>
using namespace std;
int main()
{
int number;
while (cin >> number)
{
cout << 2 * number - 1 << " " << flush;
}
return 0;
}
Ok so pipeline.cpp : forks twice and creates a pipe between the two children. Then each use excel to replace its process with the programs part1 and part2. So my understanding is that part1 program would run and anything it outputs will be picked up by the second child which runs part2 and from there part two would output normally since it's output descriptor wasn't changed. Am I missing or misusing something here?
I noticed a couple of things:
You're not passing the number to the part1 process when you exec it
You're not checking for failure from execl() or any of the other OS functions
I think once you do these two things, you'll find out what the real problem is. I won't just tell you what the answer is, because it's worthwhile learning how to diagnose such problems yourself. (I was able to run your code successfully with only minor modifications. The problem does not lie in how you're handling the pipes and file descriptors.)
I think you need to return 0; after your exec calls. But I am even more lost than you it seems.