How to ensure only one copy of the application is running? [duplicate] - c

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Preventing multiple process instances on Linux
I have multi-threaded application which can be run as a deamon process or one time with input parameters.
I want to ensure that if the application is running as a deamon process then, user should not be allowed to run this again.
EDIT:After you all suggested to go for flocks, I tried it and put it in server. I know have weird problem, when the servers are bounced, they delete all the files, including lock file :(. How now ?

The easiest way is to bind to a port (could be unix domain, in a "private" directory) Only one process can bind to a port, so if the port is bound, the process is running. If the process exits, the kernel automatically closes the filedescriptor. It does cost your process a (unused?) filedescriptor. Normally a daemon process would need some listen socket anyway.

You can try using file locks. Upon starting the process, you can open a file, lock it, and check for a value (e.g. size of file). If it's not desired value, the process can exit. If desired value, change the file to an undesired value.

I implemented similar thing by using shell scripts to start and stop the daemon.
In the start script before the exe call look if this exe is still running. If it finds it is still running then new process is not started.

Related

How to share log files with multiple processes?

This is more design question to hear ideas from other people.
I'm writing a software written in c language completely.
It has multiple processes running and now I'm thinking to add logging.
First idea is writing a simple log function may be in separate library.
Then, I may need to add some kind of lock to prevent race condition to access the log file.
The second idea is spawning a separate log process and the log process is accessing the log file.
And the other processes can send log message to the log process using IPC mechanism such as pipe or unix socket.
In that case, is there any way to set buffer for the pipe or unix socket?
Or it is not worth to consider buffering for IPC recipient?

What is the most suitable IPC between programs in C

I've been building 2 programs in C. The first program is a service that automatically shutdowns the pc if the time is past 22:00 with a countdown of 1 minutes. And at the same time it opens the second program and ask for username and password via ShellExecution in winapi. If the login is successful in the second program then the shutdown is totaly canceled. Then when the second program is closed or terminated then the shutdown process repeats all over again if the time is still past 22:00. My problem is how should I allow or make this kind of communication to happen between the two program. I'm thinking of using shared memory or pipe. I'm not sure what kind of ipc is suitable for this kind of situation. Note that if the second program is already open and logged in the shutdown process would not occure. And it should have no problem even if multiple instances of the second program is open and logged in.
I don't know if you need another process. I'd be tempted to do the login/password with another thread. That gives you shared memory with little effort.
Not being a crack Windows programmer, I don't know if you can do the ShellExecution in another thread, or if protections will get in your way.
If it didn't work and you had to do another process, I'd try a UNIX style pipe but those don't exist on Windoes, you get to a named pipes. Pipe are usually better than shared memory for security and complexity reasons. A trick is to make sure that only the correct program is on the other end of the pipe. That may or may not matter depending on how clever you expect an attacker to be.

Restarting inetd should effect instances of all inetd controlled processes

When I am sending HUP signal to inetd so that it rereads the new inetd.conf file, what I want is, the processes controlled by the inetd process should also restart, so that it can read the new command line parameters added to the inetd.conf file as part of the change.
I know I can search for the running process and kill it, but is there a standard way to do this. I could not find anything over the Internet.
The standard inetd included in NetBSD does not manage the processes it starts (except for single-threaded services, i.e. those with "wait" flags) -- it just starts them. Each child process services one active connection and then exits when done (i.e. when the connection is closed). In the general case it would be very unwise to kill such processes early without very good reason -- for example consider the case where your current login session (where you tell inetd to reload) was opened to a service controlled by inetd (e.g. sshd).
If you really want to kill processes handling active current connections then you will have to write some helper script of your own to do that, though perhaps pkill will suffice.

Any possible solution to capture process entry/exit?

I Would like to capture the process entry, exit and maintain a log for the entire system (probably a daemon process).
One approach was to read /proc file system periodically and maintain the list, as I do not see the possibility to register inotify for /proc. Also, for desktop applications, I could get the help of dbus, and whenever client registers to desktop, I can capture.
But for non-desktop applications, I don't know how to go ahead apart from reading /proc periodically.
Kindly provide suggestions.
You mentioned /proc, so I'm going to assume you've got a linux system there.
Install the acct package. The lastcomm command shows all processes executed and their run duration, which is what you're asking for. Have your program "tail" /var/log/account/pacct (you'll find its structure described in acct(5)) and voila. It's just notification on termination, though. To detect start-ups, you'll need to dig through the system process table periodically, if that's what you really need.
Maybe the safer way to move is to create a SuperProcess that acts as a parent and forks children. Everytime a child process stops the father can find it. That is just a thought in case that architecture fits your needs.
Of course, if the parent process is not doable then you must go to the kernel.
If you want to log really all process entry and exits, you'll need to hook into kernel. Which means modifying the kernel or at least writing a kernel module. The "linux security modules" will certainly allow hooking into entry, but I am not sure whether it's possible to hook into exit.
If you can live with occasional exit slipping past (if the binary is linked statically or somehow avoids your environment setting), there is a simple option by preloading a library.
Linux dynamic linker has a feature, that if environment variable LD_PRELOAD (see this question) names a shared library, it will force-load that library into the starting process. So you can create a library, that will in it's static initialization tell the daemon that a process has started and do it so that the process will find out when the process exits.
Static initialization is easiest done by creating a global object with constructor in C++. The dynamic linker will ensure the static constructor will run when the library is loaded.
It will also try to make the corresponding destructor to run when the process exits, so you could simply log the process in the constructor and destructor. But it won't work if the process dies of signal 9 (KILL) and I am not sure what other signals will do.
So instead you should have a daemon and in the constructor tell the daemon about process start and make sure it will notice when the process exits on it's own. One option that comes to mind is opening a unix-domain socket to the daemon and leave it open. Kernel will close it when the process dies and the daemon will notice. You should take some precautions to use high descriptor number for the socket, since some processes may assume the low descriptor numbers (3, 4, 5) are free and dup2 to them. And don't forget to allow more filedescriptors for the daemon and for the system in general.
Note that just polling the /proc filesystem you would probably miss the great number of processes that only live for split second. There are really many of them on unix.
Here is an outline of the solution that we came up with.
We created a program that read a configuration file of all possible applications that the system is able to monitor. This program read the configuration file and through a command line interface you was able to start or stop programs. The program itself stored a table in shared memory that marked applications as running or not. A interface that anybody could access could get the status of these programs. This program also had an alarm system that could either email/page or set off an alarm.
This solution does not require any changes to the kernel and is therefore a less painful solution.
Hope this helps.

Mutex definition and use in C

I am writing a program using C. I want to have a mutex which can help me to run a new instance of a program in case the first instance of my program lost or stopped working.
I don't know how to start ...
Any help would be really great.
If you are using Windows, then make a named mutex with CreateMutex. The first instance to run creates the mutex if it does not yet exists and locks it. Additional instances will fail to get ownership of the mutex using WaitForSingleObject and should terminate.
On Unix-like systems, it is typically to write the first instance's PID to a lock file. Other instances would then check that file versus the currently running programs. This is a bit more involved and does not utilize mutexes.
It seems I misread your question a bit and the prose above addresses the opposite: ensuring that only one instance runs at a time. To restart your process if it hangs or fails is more complicated. I would suggest a program that launches your application and monitors its health externally. The launcher could then start new instances when it detects a problem. The exact process is highly dependent on your platform.
You create a small loop that starts your program. So it will restart the program if it crashes.
In linux you can do this in a simple bash script
$ while true; do ./path/my/prog; done
In C, I would guess you write:
while(1) {
system("./path/my/prog");
}

Resources