Nov 29 2009
Archive for the 'Linux' Category
Jun 12 2009
Reading outputs of an external program in C++
Ever wanted to grab the output of a command via C++?
In PHP, we are all very familiar with @exec and popen, but what about C++?
Try this:
string cmd = “/usr/bin/netstat -na”;
string OutString;
FILE *FileStream;
char stdbuffer[1024];
FileStream = popen(cmd.c_str(), “r”);
while (fgets(stdbuffer, 1024, FileStream) != NULL)
OutString.append(stdbuffer);
pclose(FileStream);
- The first 3 lines are variable declarations.
- This is followed by popen command which opens a pipe to the external program. r here means to read from the program output.
- We will now use a 1024 character buffer to read the pipe until a null terminator is encountered.
- Remember to close the process pipe once you’re done!
You ask: “What if I want to have the stderr captured as well?”. No problem! Just add:
2>&1
to the back of your command, just like how you would do it in BASH.
Mar 15 2008
Automating jobs with cron
cron is probably one of the most useful services in the UNIX world. It is a time-based scheduling service that executes commands at a set interval.
Most flavours of Linux should have cron bundled. Unfortunately, not every distribution has the same method of configuration. The following example is based on CentOS 5, a popular enterprise web server distribution based on the Red Hat Enterprise Linux.
The configuration file for cron is stored in /etc/crontab. This file stores a list of commands to execute at a certain time interval you set.
