Exposing status information from basic c/cpp Linux application - c++

I am trying to provide a query mechanism that is analogous to a /proc entry for a Kernel driver/module in Linux - except I have a userspace application.
This is running in Linux, c/cpp application. I want to accomplish something like:
$ cat /proc/myapp/status
and it calls a function in my application that prints a few lines of custom status info.
Obviously I cannot use proc from a userspace application, but what would accomplish something similar from a user app? This is embedded Linux so dbus is most likely not available

There's two things you need to work out. One is what the process is going to be and the other is what is going to perform the process.
As for what the process is going to be, it can be almost anything you want. For example, you could send a signal (like SIGUSR1) to the process and it writes its status to a file. You could have a UNIX domain local socket that you connect to and it writes its status. You have lots of options.
The second thing is what will actually perform the process. One way would be to start your application with a special command line option, like --status, and it executes the steps needed to produce the status and writes them to standard output. That would allow you to do things like MyApplication --status to see the status or MyApplication --status | SomeOther Application to send the status to some other application.
You could just have a logfile open that the status gets written to when SIGUSR1 is received. Then you can use a version of tail -f <logfile> followed by using kill to send SIGUSR1 to your application.
It's up to you. There's no "one right way".

I think you can get it with a deamon application.
You can use pthread library in your application, so that you can keep on your latest information on any files.
Although, it must have done more than using proc file system you can do what you want.

Related

Start/Stop daemon on Linux via C++ code

I am trying to find out a way to launch a custom daemon from my program. The daemon itself is implemented using double-forking mechanism and works fine if launched directly.
So far I have come across various ways to start a daemon:
Create an init script and install it to init.d directory.
Launch the program using start-stop-daemon command.
Create .desktop file and place in one of the autostart paths.
While the 1st 2 methods are known to start the service using command line, the 3rd method is for autostarting the service (or any other application) at user login.
So far my guess is that the program can be executed directly using exec() family of functions, or the 'start-stop-daemon' command can be executed via system() function.
Is there a better way to start/stop service?
Generally startups are done from shell scripts that would call your C++ program which would then do its double fork. Note that it should also close unneeded file descriptors, use setsid() and possibly setpgid/setpgrp (I can't remember if these apply to Linux too), possibly chdir("/"), etc. There are a number of fairly normal things to do which are described in the Stevens book - for more info see http://software.clapper.org/daemonize/daemonize.html
If the daemon is supposed to run with root or other system user account, then the system /etc/init/ or /etc/init.d/ mechanisms are appropriate places to have scripts to stop|start|status|etc your daemon.
If the deamon is supposed to be for the user, and run under his/her account, you have a couple of options.
1) the .desktop file - I'm not personally a fan, but if it also does something for you on logging out (like let you trigger shutting down your daemon), it might be viable.
2) For console logins, the ~/.bash_login and ~/.bash_logout - you can have these run commands supported by your daemon's wrapper to start it and (later) shut it down. The latter can be done by saving the PID in a file or having the .bash_login keep it in a variable the .bash_logout will use later. This may involve some tweaking to make sure the two scripts get run, once each, by the outermost login shell only (normal .bashrc stuff stays in the .bashrc, and .bash_login would need to read it in for the login shell before starting the daemon, so the PATH and so on would be set up by then).
3) For graphic environments, you'd need to find the wrapper script from which things like your X window manager are run. I'm using lightdm, and at some point /etc/X11/Xsession.d/40x11-common_xsessionrc ends up running my ~/.xsessionrc which gives me a hook to startup anything I want (I have it run my ~/.xinitrc which runs my window manager and everything), as well as the place to shot everything down later. The lack of standardization for giving control to the user makes finding the hook pretty annoying, since just using a different login manager (e.g. lightdm versus gdb) can change where the hook is.
4) A completely different approach is to just have the user's crontab start up the daemon. Run "man 5 crontab" and look for the special #reboot option to have tasks run at boot. I haven't used it myself - there's a chance it's root restricted, but it's easy to test and you need only contemplate having your daemon exist gracefully (and quickly) at system shutdown when the system sends it a SIGTERM signal (see /etc/init.d/sendsigs for details).
Hope something from that helps.

Access data from terminal

I have to write a program that intercepts data from terminal and i have to parse it. After processing when the data, i have to parse it before it goes to stdout.
I can't use tee or commands like prog > file 2>&1 as the program is going to be interactive.
For example :
If the user types ls in the terminal i have to parse it then it should go operating system and then when I get the result after processing I ll have to again parse it before it's displayed in the terminal.
I did my research and I think I can achieve it through pseudo terminal interfaces ( pty ).
Please let me know if there is a better way to achieve it.
I am using cpp and bash and the platform is *nix.
Update:
I can also use libexpect from expect.
I am not sure what do you mean here - you mean interactive program as "working in another terminal communicating with user" or even displaying GUI?
How does it specify the terminal? It is probably important what is program layout here (which program starts which).
If your application uses GUI to communicate with user, then I would simply do it this way:
start bash with sdtin and stdout attached to pipes,
your program reads & writes to it's end's of those pipes, parses data, and reads/writes on it's own stdin&stdout - so it appears on it's terminal.
If you mean controlling different terminal than your application's, it gets though since system generally does not expect program operating on multiple terminals. I don't think it's possible to filter communication between terminal and already working application attached to it. Starting another process spawning another terminal might be an option - to have basically two terminals working in sync. But then you will have to synchronize both processes by some other means (named pipes, network connection or some other IPC).
If you provide more detail on your program I might provide more directed help.
PS Don't tell me that you are writing some terminal keylogger ')
EDIT:
Your program is probably GUI based then - what i would recommend would be something similar to answer linked by banuj.
Best option will probably be to create three pipes, then fork, and in child process assign corresponding ends of pipes to stdin, stdout and stderr. Then child process should exec into shell - probably bash, although I am not sure if other shells would sound better if read out loud ;) Main process will be able to read/write other ends of mentioned pipes, parsing both inputs and outputs to bash and programs it runs.
You could also exec directly to commands user specifies, but that forces you to take over tedious job of a shell - managing current directory, environment variables, job control and so on.
Using above method might however cause some trouble - some programs (usually in security related contexts - eg. su(do) asking for password) will try to bypass stdin/stdout anyway and read directly from terminal device. I am not sure what can you do in such case - programing your own terminal emulator would be an option, but I don't know if you want to go this deep into system programming for this.
If you want some code snippet's, if you don't know how to do above, just ask ;)

Catching system events in C Linux

I am writing an application on Linux which requires me to catch system events like:
System reboot
User 'xyz' logs in
'xyz' application crashes etc.
and need to execute some functionality based on that. For e.g.:
Run backup script
Run recovery program etc.
Can anyone please tell me how to catch system events in C/Linux ?
P.S: I am not talking about 'file system' events here :P
There is no concept of "system event". You need to specify which events you need to handle and implement appropriate mechanism for handling each:
System startup: The init process calls scripts from /etc/init.d during startup. The exact infrastructure differs slightly between distributions, but Linux Standards Base System Initialization should generally work on all.
User login/logout: The LSB also defines interface to the Pluggable Authentication Modules library. You can implement a shared library that will be called during login (and also other actions that require authentication and authorization). Depending on what you want to do there may already be a module that will work for you, so try looking for it first. In either case I don't think there is distribution-independent way of installing it and even on given distribution you have to consider that administrator might have made custom modification, so the installation will need manual intervention by the administrator.
Application crashes: You would have to instrument it.
I think you should consider reading systems logs - everything you ask about is logged to the syslog (for standard configuration). If your system uses syslog-ng, then you could even configure it to write directly to your program, see http://www.syslog.org/syslog-ng/v2/#id2536904 for details. But even with any other syslog daemon, you can always read file (or files) from /var/log just like tail -f does, end react on particular messages.
I'm not sure about catching application crashes - there's a kernel option to log every SIGSEGV in user processes, but AFAIK it is available only on ARM architecture - last resort would be to instrument your application (as Jan Hudec pointed out) to log something to syslog.

How to make a process aware of other processes of the same program

I must write a program that must be aware of another instance of itself running on that machine, and communicate with it, then die. I want to know if there is a canonical way of doing that in Linux.
My first thought was to write a file containing the PID of the process somewere, and look for that file every time the program executes, but where is the "right" place and name for that file? Is there a better, or more "correct" way?
Then I must communicate, saying the user tried to run it, but since there is another instance it will hand over the job and exit. I thought of just sending a signal, like SIGUSR1, but that would not allow me to send more information, like the X11 display from where the user executed the second process. How to send this info?
The program is linked against Gtk, so a solution that uses the glib is OK.
Putting the pid in a file is a common way of achieving this. For daemons ("system programs"), the common place to put such a file is /var/run/PROGRAM.pid. For user programs, put the pid file hidden in the user's homedir (if the program also has configuration files, then put both config files and the pid file in a subdir of the home dir).
Sending information to the "master" instance is most commonly achieved using Unix domain sockets, also known as local sockets. With a socket, you won't need a pid file (if no-one listens on the socket, the process knows it's master).
Unix domain sockets. Have the first instance create one in a temporary directory, then have other instances communicate with it via that.
Writing a PID file is a common approach. Check the pidfile(3) library.
Does linux have the equivalent of a named mutex or semaphore? So you can check to see if it's 'locked' and then warn the user they already have one out there and close it out?
does this make sense from this link?
http://www.linuxquestions.org/questions/programming-9/named-mutex-in-linux-296816/
There are many ways to do this. The way you proposed (using a file containing the PID) is a valid one and is used by many applications.
Some times the application's configuration file contains the path for the PID file, other times a hardcoded path is used. Usually application put the PID file in /tmp, in /var (if they run with uid 0) or in their local directory (~/.application/).
Wouldn't have a general suggestion on where to put your PID file, just choose the place you prefer.
You can certainly use a Unix domain socket; I think most applications (which don't use a higher-level system like DCOP or DBUS) use these.
If you're happy for it to be Linux-specific, you can use an "abstract namespace" unix socket; these are rather nice because they don't need to exist in the filesystem.
If your program is user-oriented, it should probably be multiuser aware; one user should not be able to trigger behaviour in another user's copy of the app, and security needs to be in place to ensure that users cannot DoS each other easily either (Example: if user A's copy of the program hangs, does it stop user B's from starting?).

How to know if a process had been started but crashed in Linux

Consider the following situation: -
I am using Linux.
I have doubt that my application has crashed.
I had not enabled core dump.
There is no information in the log.
How can I be sure that, after the system restart my app was started, but now it is not running, because it has crashed.
My app is configured as a service, written in C/C++.
In a way: how can I get all the process/service names that have executed since the system start? Is it even possible?
I know, I can enable logging and start the process again to get the crash.
This feature is included in Linux Kernel. It's called: BSD process accounting.
Standard practice is to have a pid file for your daemon (/var/run/$NAME.pid), in which you can find its process id without having to parse the process tree manually. You can then either check the state of that process, or make your daemon respond to a signal (usually SIGHUP), and report its status. It's a good idea to make sure that this pid still belongs to your process too, and the easiest way is to check /proc/$PID/cmdline.
Addendum:
If you're only using newer fedora or ubuntu, your init system is upstart, which has monitoring and triggering capabilities built in.
As #emg-2 noted, BSD process accounting is available, but I don't think it's the correct approach for this situation.
I would recommend that you write the fact that you started out to some kind of log file, either a private one which get's overwritten on each start up or one via syslogd.
Also, you can log a timestamp heartbeat so that you know exactly when it crashed.
you probably can make a decoy, ie an application or shell script that is just a wrapper around the true application, but adds some logging like "Application started".
Then you change the name of your original app, and give the original name to your decoy.
As JimB mentions, you have the daemon write a PID file. You can tell if it's running or not by sending it a signal 0, via either the kill(2) system call or the kill(1) program. The return status will tell you whether or not the process with that PID exists.
Daemons should always:
1) Write the currently running instance's process to /var/run/$NAME.pid using getpid() (man getpid) or an equivalent command for your language.
2) Write a standard logfile to /var/log/$NAME.log (larger logfiles should be broken up into .0.log for currently running logs along with .X.log.gz for other logs, where X is a number with lower being more recent)
3) /Should/ have an LSB compatible run script accepting at least the start stop status and restart flags. Status could be used to check whether the daemon is running.
I don't know of a standard way of getting all the process names that have executed; there might be a way however to do this with SystemTap.
If you just want to monitor your process, I would recommend using waitid (man 2 wait) after the fork instead of detaching and daemonizing.
If your app has crashed, that's not distinguishable from "your app was never started", unless your app writes in the system log. syslog(3) is your friend.
To find your app you can try a number of ideas:
Look in the /proc filesystem
Run the ps command
Try killall appname -0 and check the return code