Do other tasks while a system() command is being executed - c++

I have this c++ program that is doing a simple ping on a specified ip address. I am not into networking so i'm just using the system() command in c++ to execute the ping from a shell and store the results in a file, that's easy.
The problem is that i want some dots to be printed on the screen while the system() command is being executed. i tried with:
while(system(cmd))
{
//execute the task here
}
but no success. I think that i should create threads or something.
Can you help me ? What exactly i am supposed to do in order to get this done as i want to ?

The problem with system is that it suspends execution until completion. On unix systems you will need to use a sequence of fork, execv, dup2 and pipe. This will allow you to do something more useful. See http://docs.linux.cz/programming/c/unix_examples/execill.html for an example.

You need to create a forked process using fork, like this, and using popen to read the input from the output of the command ping google.com and process it accordingly. There is an interesting guide by Beej on understanding the IPC mechanisms which is included in the code sample below...
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(void)
{
pid_t pid;
int rv;
FILE *ping;
char buf[2000];
switch(pid = fork()) {
case -1:
perror("fork"); /* something went wrong */
exit(1); /* parent exits */
case 0:
// We're the child
ping = popen("ping google.com", "r");
if (ping != NULL){
fgets(buf, sizeof(buf), ping);
pclose(ping);
rv = 0;
}else{
perror("popen failed");
rv = -1;
}
exit(rv);
default:
// We're the parent...
wait(&rv);
}
// Now process the buffer
return 0;
}
Hope this helps,
Best regards,
Tom.

Edit On consideration, I believe that popen is the way to go with or without output from cmd.
Older
You are probably looking for something in the wait (2) family of commands plus a fork and exec.
From the manual page
The wait() function suspends execution of its calling process until
stat_loc information is available for a terminated child process, or a
signal is received. On return from a successful wait() call, the
stat_loc area contains termination information about the process that
exited as defined below.
Or if cmd returns some progress information you want popen (3) which is discussed in a number of existing SO questions; for instance How can I run an external program from C and parse its output?.

If you are on a unix system, you can start a command with an & to indicate that it runs in the background like this: myscript &
This will start a new process separate from the current program. You need to pick up the process number (hopefully from system, my c posix api knowledge is rusty) and then check up on it probably with a call to something like wait or waitpid with non-blocking turned on.
This is complicated for a beginner -- I'll let someone else post details if still interested.

Related

Modern C++ way of starting and terminating a linux program

I have a C++ program that, based on user input, needs to start and stop a given Linux program.
I've simplified the logic I'm currently using in the following code:
int pid = fork();
if (pid == -1)
{
//Handle error
}
else if (pid == 0)
{
execlp("my_program", nullptr);
exit(0);
}
else
{
//Main program stuff
if(/* user selects close "my_program"*/)
{
kill(pid, SIGTERM);
}
//Other main program stuff
}
Everything is working, but I was wondering if there were any other approaches, maybe more in the modern C++ style, that could be used in this situation.
Thanks in advance.
Take a look at boost::process.
There are several ways a process can be spawned. For example, in your example, you fork the process, but you don't close the cloned file descriptors in the child process. That is an often forgotten practice by those that invoke fork and can lead to binding to port problems (port/address already in use) or other hard-to-debug issues.
Even boost didn't do that quite correctly for some time.
The modern way would be to use a library like Boost.Process https://www.boost.org/doc/libs/1_78_0/doc/html/process.html or Qt https://doc.qt.io/qt-5/qprocess.html.

how a daemonize a c/c++ program on Linux

I wrote a daemon program on Linux according to the guide at http://linux.die.net/man/1/daemonize, but the process crashed several times and I cannot find the reason. It has troubled me for a few days.
Today I happened to have read 'UNIX network Programming
volume 1, Third Edition' by W.Richard Stevens. And in this book, it shows an example to write daemon program. After reading the example, I realized 'Disassociate from the control terminal' is missing from my code.
Now my question is to daemonize a process, why we need disassociate from the control terminal? And does it related to the crash of the process? Is there any other place is missing in my code for daemonize?
Appreciate your replies.
Here is my code:
bool daemonize()
{
// http://linux.die.net/man/1/daemonize
// change working dir to root
(void) uchdir("/");
// close stdin, stderr, stdout
if (int fdnull = open("/dev/null", O_RDWR))
{
dup2 (fdnull, STDIN_FILENO);
dup2 (fdnull, STDOUT_FILENO);
dup2 (fdnull, STDERR_FILENO);
close(fdnull);
}
else
{
Log (ERR, "Failed to open /dev/null");
return false;
}
// detach from previous process group
if (setsid () == -1) /* request a new session (job control) */
{
Log (ERR, "Failed to detach from previous process group");
return false;
}
// inhibit others completely and group write
umask(027);
// it's dameonized!
return true;
}
The basic steps to deamonize a C or C++ program have already been mentioned in this question: Creating a daemon in Linux
Yes, the question there was for C and not for C++, but since the system calls you need to daemonize a program are C functions in both cases, that really does not make a difference.
I found this github repository useful, it has what you need to build a daemon:
Simple example of daemon for Linux
And here is a stack overflow thread why double fork is nessesary.
Not addressing your actual question but…
I wrote a daemon program on Linux according to the guide at [http://linux.die.net/man/1/daemonize][1],
please don't!
Programs that daemon-ize are the bane of any sensible init system and service tracker. The problem is, that after a program detaches from its controlling terminal and parent process it gets difficult to keep track about its state and regain control over it. The usual way of using PID files is prone to race conditions, which is especially bad if the intention is to automatically respawn such a process.
The use of daemon led to the development of several hacks, some outright ugly some kind of okay, but none of them being beautiful. Do yourself and the rest of the world a favour and don't daemonize your program.

pidof from a background script for another background process

I wrote a c++ program to check if a process is running or not . this process is independently launched at background . my program works fine when I run it on foreground but when I time schedule it, it do not work .
int PID= ReadCommanOutput("pidof /root/test/testProg1"); /// also tested with pidof -m
I made a script in /etc/cron.d/myscript to time schedule it as follows :-
45 15 * * * root /root/ProgramMonitor/./testBkg > /root/ProgramMonitor/OutPut.txt
what could be the reason for this ?
string ReadCommanOutput(string command)
{
string output="";
int its=system((command+" > /root/ProgramMonitor/macinfo.txt").c_str());
if(its==0)
{
ifstream reader1("/root/ProgramMonitor/macinfo.txt",fstream::in);
if(!reader1.fail())
{
while(!reader1.eof())
{
string line;
getline(reader1,line);
if(reader1.fail())// for last read
break;
if(!line.empty())
{
stringstream ss(line.c_str());
ss>>output;
cout<<command<<" output = ["<<output<<"]"<<endl;
break;
}
}
reader1.close();
remove("/root/ProgramMonitor/macinfo.txt");
}
else
cout<<"/root/ProgramMonitor/macinfo.txt not found !"<<endl;
}
else
cout<<"ERROR: code = "<<its<<endl;
return output;
}
its output coming as "ERROR: code = 256"
thanks in advacee .
If you really wanted to pipe(2), fork(2), execve(2) then read the output of a pidof command, you should at least use popen(3) since ReadCommandOutput is not in the Posix API; at the very least
pid_t thepid = 0;
FILE* fpidof = popen("pidof /root/test/testProg1");
if (fpidof) {
int p=0;
if (fscanf(fpidof, "%d", &p)>0 && p>0)
thepid = (pid_t)p;
pclose(fpidof);
}
BTW, you did not specify what should happen if several processes (or none) are running the testProg1....; you also need to check the result of pclose
But you don't need to; actually you'll want to build, perhaps using snprintf, the pidof command (and you should be scared of code injection into that command, so quote arguments appropriately). You could simply find your command by accessing the proc(5) file system: you would opendir(3) on "/proc/", then loop on readdir(3) and for every entry which has a numerical name like 1234 (starts with a digit) readlink(2) its exe entry like e.g. /proc/1234/exe ...). Don't forget the closedir and test every syscall.
Please read Advanced Linux Programming
Notice that libraries like Poco or toolkits like Qt (which has a layer QCore without any GUI, and providing QProcess ....) could be useful to you.
As to why your pidof is failing, we can't guess (perhaps a permission issue, or perhaps there is no more any process like you want). Try to run it as root in another terminal at least. Test its exit code, and display both its stdout & stderr at least for debugging purposes.
Also, a better way (assuming that testProg1 is some kind of a server application, to be run in at most one single process) might be to define different conventions. Your testProg1 might start by writing its own pid into /var/run/testProg1.pid and your current application might then read the pid from that file and check, with kill(2) and a 0 signal number, that the process is still existing.
BTW, you could also improve your crontab(5) entry. You could make it run some shell script which uses logger(1) and (for debugging) runs pidof with its output redirected elsewhere. You might also read the mail perhaps sent to root by cron.
Finally I solved this problem by using su command
I have used
ReadCommanOutput("su -c 'pidof /root/test/testProg1' - root");
insteadof
ReadCommanOutput("pidof /root/test/testProg1");

How to prevent a Linux program from running more than once?

What is the best way to prevent a Linux program/daemon from being executed more than once at a given time?
The most common way is to create a PID file: define a location where the file will go (inside /var/run is common). On successful startup, you'll write your PID to this file. When deciding whether to start up, read the file and check to make sure that the referenced process doesn't exist (or if it does, that it's not an instance of your daemon: on Linux, you can look at /proc/$PID/exe). On shutdown, you may remove the file but it's not strictly necessary.
There are scripts to help you do this, you may find start-stop-daemon to be useful: it can use PID files or even just check globally for the existence of an executable. It's designed precisely for this task and was written to help people get it right.
Use the boost interprocess library to create a memory block that will be created by the process. If it already exists, it means that there is another instance of the process. Exit.
The more precise link to what you need would be this one.
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/scoped_ptr.hpp>
int main()
{
using boost::interprocess;
boost::scoped_ptr<shared_memory_object> createSharedMemoryOrDie;
try
{
createSharedMemoryOrDie.reset(
new shared_memory_object(create_only, "shared_memory", read_write));
} catch(...)
{
// executable is already running
return 1;
}
// do your thing here
}
If you have access to the code (i.e. are writing it):
create a temporary file, lock it, remove when done, return 1; if file exists, or,
list processes, return 1; if the process name is in the list
If you don't:
create a launcher wrapper to the program that does one of the above
I do not know what your exact requirement is but I had a similar requirement; in that case I started my daemon from a Shell script ( it was a HP-UX machine) and before starting the daemon I checked if an exec by same name is already running. If it is; then don't start a new one.
By this way I was also able control the number of instances of a process.
I think this scheme should work (and is also robust against crashes):
Precondition: There is a PID file for your application (typically in /var/run/)
1. Try to open the PID file
2. If it does not exist, create it and write your PID to it. Continue with the rest of the program
3. If it exist, read the PID
4. If the PID is still running and is an instance of your program, then exit
5. If the PID does not exist or is used by another program, remove the PID file and go to step 2.
6. At program termination, remove the PID file.
The loop in step 5 ensures that, if two instances are started at the same time, only one will be running in the end.
Have a pid file and on the startup do a 'kill -0 <pid>'. Where is the value read from file. If the response is != 0 then the daemon is not alive and you might restart it
Another approach would be to bind to a port and handle the bind exception on the second attempt to start the daemon. If the port is in use then exit otherwise continue running the daemon.
I believe my solution is the simplest:
(don't use it if racing condition is a possible scenario, but on any other case this is a simple and satisfying solution)
#include <sys/types.h>
#include <unistd.h>
#include <sstream>
void main()
{
// get this process pid
pid_t pid = getpid();
// compose a bash command that:
// check if another process with the same name as yours
// but with different pid is running
std::stringstream command;
command << "ps -eo pid,comm | grep <process name> | grep -v " << pid;
int isRuning = system(command.str().c_str());
if (isRuning == 0) {
cout << "Another process already running. exiting." << endl;
return 1;
}
return 0;
}

Problems with system() calls in Linux

I'm working on a init for an initramfs in C++ for Linux. This script is used to unlock the DM-Crypt w/ LUKS encrypted drive, and set the LVM drives to be available.
Since I don't want to have to reimplement the functionality of cryptsetup and gpg I am using system calls to call the executables. Using a system call to call gpg works fine if I have the system fully brought up already (I already have a bash script based initramfs that works fine in bringing it up, and I use grub to edit the command line to bring it up using the old initramfs). However, in the initramfs it never even acts like it gets called. Even commands like system("echo BLAH"); fail.
So, does anyone have any input?
Edit: So I figured out what was causing my errors. I have no clue as to why it would cause errors, but I found it.
In order to allow hotplugging, I needed to write /sbin/mdev to /proc/sys/kernel/hotplug...however I ended up switching around the parameters (on a function I wrote myself no less) so I was writing /proc/sys/kernel/hotplug to /sbin/mdev.
I have no clue as to why that would cause the problem, however it did.
Amardeep is right, system() on POSIX type systems runs the command through /bin/sh.
I doubt you actually have a legitimate need to invoke these programs you speak of through a Bourne shell. A good reason would be if you needed them to have the default set of environment variables, but since /etc/profile is probably also unavailable so early in the boot process, I don't see how that can be the case here.
Instead, use the standard fork()/exec() pattern:
int system_alternative(const char* pgm, char *const argv[])
{
pid_t pid = fork();
if (pid > 0) {
// We're the parent, so wait for child to finish
int status;
waitpid(pid, &status, 0);
return status;
}
else if (pid == 0) {
// We're the child, so run the specified program. Our exit status will
// be that of the child program unless the execv() syscall fails.
return execv(pgm, argv);
}
else {
// Something horrible happened, like system out of memory
return -1;
}
}
If you need to read stdout from the called process or send data to its stdin, you'll need to do some standard handle redirection via pipe() or dup2() in there.
You can learn all about this sort of thing in any good Unix programming book. I recommend Advanced Programming in the UNIX Environment by W. Richard Stevens. The second edition coauthored by Rago adds material to cover platforms that appeared since Stevens wrote the first edition, like Linux and OS X, but basics like this haven't changed since the original edition.
I believe the system() function executes your command in a shell. Is the shell executable mounted and available that early in your startup process? You might want to look into using fork() and execve().
EDIT: Be sure your cryptography tools are also on a mounted volume.
what do you have in initramfs ? You could do the following :
int main() {
return system("echo hello world");
}
And then strace it in an initscript like this :
strace -o myprog.log myprog
Look at the log once your system is booted