Interrupt a running c++ program from another program or terminal - c++

I have written a c++ program which has a infinite loop. I want to run this program as a daemon (or service) in linux.
I want to communicate with this running daemon from outside of program (for example console or another program).
I read about signal handling in c++ and apparently there are some predefined signals. Is there any way to send your own signal to the running program?

Signals are most probably not what you really want to communicate with a demon process, unless you want to terminate it in a specific manner.
Also no, you can't define your own arbitrary signal numbers, as the operating system needs to know how they are sent to the process. As mentioned in my comment there are the SIGUSR1 and SIGUSR2 were intended for user defined signalling purposes.
The easiest way to let an external process communicate with a demon process, is to give it a configuration file, and let the demon watch for changes using the inotify() interface.
This technique is also used by many system demons already.

You can use kill(pid, signal) from one process to send signal to another. Sending SIGKILL will violently and instantly terminate your process.
Signals are limited to what they express - and you can find that out by accessing page 7 of signal manual. Some signals can be ignored/handled/blocked while others cannot.
If you want true custom inter-process communication you should use pipes or even sockets (bad practice). This way, you would have to define your own protocol and you can do a lot more than with signals.
Here's a tutorial on how to use named pipes to send data to running processes: http://www.linuxjournal.com/content/using-named-pipes-fifos-bash.

Related

Detect wakeup computer using C++ on linux

I don't know how can i detect that the computer has been waken up, or even I would prefer to detect wake-up on lan. I have no idea what is the common way, I found that in /etc/pm/sleep.d I can add a custom script, but i need to get invoked inside my C++ application. Now i know I could also add a custom executable written in C++ and send a socket and listen for it somewhere else but that sounds too complicated.
Your C++ application is a daemon? You may add a shell script to /etc/pm/sleep.d which should send a signal to your C++ application (SIGUSR1, for example). Inside C++ application you need to catch this signal.
see
man kill
man 7 signal
man signal
This is similar to solution with sockets but easier.

C++ signal listener for non-child pid

I'm using C++ and I need the equivalent of SIGCHLD for a process I'm aware of (i.e. I know it's pid), but did not spawn.
Is there a well established design pattern to listen/watch/monitor another process's lifespan when it is not your child or in your group or session?
EDIT: I am specifically trying to be aware of abnormal terminations (i.e. seg faults, signals, etc...). I would like to eavesdrop on signals the process in question receives.
I don't know if it follows a specific pattern, per se, but one technique is to have the process establish a connection to the watcher. The watcher monitors the connection, and when it becomes closed, it knows the process has shutdown.
If the watcher wants to know if the watched process is responsive or not, you can use the connection to monitor heartbeat messages that the process is obliged to provide.
If the watcher wants to know whether the watched process is making progress, the heartbeat message could provide state information that would allow the watcher to monitor that.
Different operating systems may provide different ways to achieve the same objective. For example, on Linux, the watcher could use inotify to monitor the /proc entry for that process to determine if the process is up or down. The BSD kqueue has a similar capability. The process could export its heartbeat/state into shared memory, and the watcher could use a timed wait on a semaphore to see if the data is being updated.
If the process is a third-party program, and source is not available, then you would have to resort to some method similar to inotify/kqueue, or as a last resort, poll the kernel state (similar to the way the top utility works).

CLI Commands to a running process

How does GDB achieves the feat of attaching itself to a running procesS?
I need a similar capability, where i can issue CLI commands to a running process. For example, i can query the process internal state such as show total_messages_processed? How can i build support for issuing commands to a running process under linux?
Is there a library that can provide CLI communication abilities to a running process and can be extended for custom commands?
The process itself is written in c++
GDB doesn't use the CLI to communicate with its debugee; it uses the ptrace system call / API.
CLI means "command-line interface". The simplest form of communication between processes is stdin / stdout. This is achieved through pipes. For example:
ps -ef | grep 'httpd'
The standard output of ps (which will be a process listing) is connected to the standard input of grep, who will process that process listing output line-by-line.
Are you writing both programs, or you want to communicate with an already-existing process? I have no idea what "show total_messages_processed" means without context.
If you simply want the program to communicate some status, a good approach is that which dd takes: Sending the process the SIGUSR1 signal causes it to dump out its current stats to stderr and continue processing:
$ dd if=/dev/zero of=/dev/null&
[1] 19716
$ pid=$!
$ kill -usr1 $pid
$ 10838746+0 records in
10838746+0 records out
5549437952 bytes (5.5 GB) copied, 9.8995 s, 561 MB/s
Did you consider using AF_UNIX sockets in your process? or D-bus? or make it an HTTP server (e.g. using libonion or libmicrohttpd), perhaps for SOAP, or RCP/XDR
Read some books on Advanced Linux Programming, or Advanced Unix Programming; you surely want to use (perhaps indirectly) some multiplexing syscall like poll(2) perhaps above some event libary like libev. Maybe you want to dedicate a thread for that.
We cannot tell more without knowing what kind of process are you thinking of. You may have to redesign some part of it. If the process is some traditional compute-intensive thing it is not the same as a SMTP server process. In particular, if you have some event loop in the process, use & extend it for monitoring purposes. If you don't have any event loop (e.g. in a traditional number crunching "batch" application) you may need to add one.
In this case I'd suggest 'fork', which splits the currently running process into two. The parent process would read stdin, process the commands and be able to handle all memory that is shared between the two processes. One could theoretically even skip advanced forms of interprocess communication: locks, mutexes, semaphores, signals, sockets or pipes -- but be prepared that the child process has not necessarily written it's state to memory but keeps it in registers.
At fork Operating System makes a copy of the process local variables, after which each process have their own internal state -- thus the easiest method for passing data would be to allocate "shared memory".
One can also write a signal handler to the child process, that goes to sleep/wait state and exits only on another signal -- in that way one can have more time to inspect the child processes internal state. The main rationale for this kind of approach is that one doesn't have to make the process under debugging aware of being debugged: the parent and child processes share the same code base and it's enough for the parent process to implement necessary output methods (formatting to screen?) and serializing the data etc.

xmlrpc server in dll, sending signal to myself?

I'm writing some dll (on windows in MSVC++2008) which provides some functionality as xmlrpc server. To implement xmlrpc server I'm using xmlrpc-c library.
I can start xmlrpc server in some diffrent ways. More intresting are:
run method - This will run xmlrpc server forever so dll can't control until server is not terminated.
runOnce method - This will run xmlrpc server only to process one RPC. And if there is no request it will wait for that.
I can't keep control in dll for long time. I need to process some RPCs and give back control to program which is using dll. And process next RPCs when dll will get back control again.
runOnce looks ok. But there is possibility that there will be no RPCs to process and it will be waiting for one. That is unacceptable.
There is also one exception:
runOnce aborts waiting for a
connection request and returns
immediately if the process receives a
signal. Note that unless you have a
handler for that signal, the signal
will probably kill the whole process,
so set up a signal handler — even one
that does nothing — if you want to
exploit this. But before Xmlrpc-c 1.06
(June 2006), signals have no effect —
there is no way to make runOnce abort
the wait and return.
Can I use it as workaround go get back control to dll? Is it possible to send signal from dll to themself? How it works on windows?
Or maybe there is some better solution of this issue?
Signals (of the kind that makes an Xmlrpc-c library call abort early) don't exist in Windows.
Best solution is to create new thread for server.

Interprocess Communication in C++

I have a simple c++ application that generates reports on the back end of my web app (simple LAMP setup). The problem is the back end loads a data file that takes about 1.5GB in memory. This won't scale very well if multiple users are running it simultaneously, so my thought is to split into several programs :
Program A is the main executable that is always running on the server, and always has the data loaded, and can actually run reports.
Program B is spawned from php, and makes a simple request to program A to get the info it needs, and returns the data.
So my questions are these:
What is a good mechanism for B to ask A to do something?
How should it work when A has nothing to do? I don't really want to be polling for tasks or otherwise spinning my tires.
Use a named mutex/event, basically what this does is allows one thread (process A in your case) to sit there hanging out waiting. Then process B comes along, needing something done, and signals the mutex/event this wakes up process A, and you proceed.
If you are on Microsoft :
Mutex, Event
Ipc on linux works differently, but has the same capability:
Linux Stuff
Or alternatively, for the c++ portion you can use one of the boost IPC libraries, which are multi-platform. I'm not sure what PHP has available, but it will no doubt have something equivalent.
Use TCP sockets running on localhost.
Make the C++ application a daemon.
The PHP front-end creates a persistent connection to the daemon. pfsockopen
When a request is made, the PHP sends a request to the daemon which then processes and sends it all back. PHP Sockets C++ Sockets
EDIT
Added some links for reference. I might have some really bad C code that uses sockets of interprocess communication somewhere, but nothing handy.
IPC is easy on C++, just call the POSIX C API.
But what you're asking would be much better served by a queue manager. Make the background daemon wait for a message on the queue, and the frontend PHP just add there the specifications of the task it wants processed. Some queue managers allow the result of the task to be added to the same object, or you can define a new queue for the finish messages.
One of the best known high-performance queue manager is RabbitMQ. Another one very easy to use is MemcacheQ.
Or, you could just add a table to MySQL for tasks, the background process just queries periodically for unfinished ones. This works and can be very reliable (sometimes called Ghetto queues), but break down at high tasks/second.