Allow start only one copy of program in linux - c

I want only one copy of my program in the system. How can I look for another copies in the system from C-code? I want something like that
# program &
[1] 12586
# program &
Program is already running
The best idea I have is making .lock-files. But I didn't find any guildlines about them.
Thank you.

One daemon I wrote opened a UNIX domain socket for regular client-daemon communication. Other instances then checked whether they could connect to that socket. If they could, another instance was currently running.
Edit: As noted by #psmears, there's a race condition. The other instances should just try to create that same listening socket. That will fail if it is already in use.
Lock files work more often than that special case. You may create an (empty) file in a well known location and then use file locks, say with fcntl(2) and F_SETLK and F_GETLK to set a lock on that file or determine whether a lock is held. May not work over NFS. Locks are cleared when your process dies, so this should work, and is portable (at least to HP-UX). Some daemons like to dump their pid into that file if they determine that no other instance is currently running.

You can use named sempahores, which is a very standard approach to this problem.
Your program calls semctl() to find if there are any active sempahores, then checks to see if you can run. If you find none, then you create the sempahore.
The OS handles the problem of processes being killed off with kill -9 and leaving sempahores.
You need to read the man page for semctl and sem_open for your machines to see what that mechanism
is.

Related

Is it possible to have a shared global variable for inter-process communication?

I need to solve a concurrency assignment for my operating systems class. I don't want the solution here, but I am lacking one part.
We should write a process that writes to file, reads from it and then deltetes it. This process we should run two times in two different shells. No fork here for simplicity. Process A should write, Process B then read and then Process should delete the file. Afterwards they switch roles.
I understand that you can achieve atomicity easily by locking. With while loops around the read-, and write sections etc. you can also get further control. But when I run process A and then process B, process B will spin before the write seciton until it achieves the lock and not got into reading when process A releases the lock. So my best guess is to have a read and a write lock. This information must be shared somehow between the processes. The only way I can think of is some global variable, but since both processes hold copies of the variables, I think this is not possible. Another way would be to have a read lock file and a write lock file, but that seems overly complicated to me.
Is there a better way?
You can use semaphores to ensure the writer and deleter wait for the previous process to finish its job. (Use man sem_init for details)
When running multiple processes with semaphores, it should be created using shared mem (man shm_open for more details).
You will need as many semaphores as the number of pipelines in this process.
You can use file as a lock. Two processes try to create a file with a previously agreed upon name using the O_EXCL flag. Only one will succeed. The one that succeeds gets the access to the resource. So in this case process A should try to create a file with name say, foo, with O_EXCL flag and, if successful, it should go ahead and write to file the information. After its work is complete, Process A should unlink foo. Process B should try to create file foo with O_EXCL flag, and if successful, try to read the file created by Process A. After its attempt is over, Process B should unlink the file foo. That way only one process will be accessing the file at any time.
Your problem (with files and alternating roles in the creation/deletion of files) seems to be a candidate to use the O_EXCL flag on opening/creating the file. This flag makes the open(2) system call to succeed in creating a file only if the file doesn't exist, so it makes the file to appear as a semaphore itself. Each process can liberate the lock (A or B) but the one that does, just liberates the lock and makes the role of owning again accessible.
You will see that both processes try to use one of the roles, but if they both try to use the owner role, one of them will succeed, and the other will fail.
Just enable a SIGINT signal handler on the owning process, to allow it to delete the file in case it gets signalled, or you will leave the file and after that no process will be able to assume the owning role (at least you will need to delete it manually).
This was the first form of locking feature in unix, long before semaphores, shared memory or other ways to block processes existed. It is based on the atomicity of system calls (you cannot execute two system calls on the same file simultaneously)

Allow opening a file with open() only in one process, in c unix programming

I'm creating an application client/server. Users registered are located in their specific file. I need that only one process of my client can login with that specific username. So I think that the best way to handle it, it's to forbid the opening of a file if it's just opened by another process, but I don't know how to do it. Suggestions? Thanks!
I have thought about semaphores but I don't think is the best solution....
ok, I'll use flock() thanks! ^^ But after open() what kind of error will give me?
Check out the system command/shell command called flock.
So as you want only one process accessing the open file, you'll be using LOCK_EX operation on the file descriptor (Assuming you're using the system call).
Please go through the man pages. man flock for shell command and man 2 flock for the system call.
If you have one multi-threaded server (but one process) that handles all the users, then it's best to just keep track of logged in users in memory. In that case, you can use mutexes (a type of semaphore) to make sure that one connection locks access to a particular user profile, and every time a new user connects, you can query your data structure. For instance, if you're using pthreads, you can define an array as follows, assuming each user has a sequential integer ID:
pthread_mutex_t YourServer::accountLocks[numberOfUsers]
If you have multiple separate processes that for some reason can't share memory, then lock files are an option. In that case, you'll have to be careful not to introduce race conditions, and you can use something like flock.
You can use flock() and set an exclusive lock on that file. This will prevent other processes than the one that set the lock to open the file.

How to avoid the binary to be launched more than one time in linux? [duplicate]

This question already has answers here:
How to create a single instance application in C or C++
(15 answers)
Closed 9 years ago.
I have a binary and it's a daemon and it's developed in C. I want to add a check at the beginning of my program to guarantee that the binary is launched only one time. My binary runs on Linux.
Any suggestions?
A common method is to put a PID file in /var/run. After your daemon starts successfully, you flock write its PID to this file. At startup, you check the value of the PID in this file, if it exists. If there is no PID currently running, it's safe for the application to startup. If the PID exists, perform a check to see if that PID is an instance of your executable. If it's not, it is also safe to startup. You should delete the file on exit, but it's not strictly necessary.
The best way to do this, in my opinion, is not to do it. Let your initialization scheme serialize instances of the daemon: systemd, runit, supervise, upstart, launchd, and so on can make sure there are no double invocations.
If you need to invoke your daemon "by hand," try the linux utility flock(1) or a 3rd-party utility like setlock. Both of these will run the daemon under the protection of a (perhaps inherited) lockfile which remains locked for the life of the program.
If you insist upon adding this functionality to the daemon itself (which, in my opinion, is complication that most daemons don't need), choose a lockfile and keep it exclusively flock(2)d. Unlike most pidfile/process table approaches, this approach is not race-prone. Unlike POSIX system semaphores, this mechanism will correctly handle the case of a crashed daemon (the lock vanishes when the process does).
There may be other easy serializations, too. If your daemon binds to a socket, you know that EADDRINUSE probably means that another instance is running...
Fork and execute this:
pidof nameOfProgram
If it returns a value, you know your program is running!
The other classic method is to have a lock file - the program creates a file, but only if that file does not already exist. If the file does exist, it presumes there's another copy of the program running. Because the program could crash after creating the file, smarter versions of this have ways to detect that situation.

how to restrict C function on server to run at most ONE instance of this function at any moment in time?

My (Linux) application server has an (ANSI) C function on it that clients may access to perform number crunching. I understand the way servers generally work is they take requests from multiple clients and process these requests in parallel. That is, the same C function on the server may be called (and more importantly, may be run) as many times as there are clients wishing to use it (assuming sufficient system resources, e.g. CPU, memory, etc.).
The problem is one call to the C function uses practically the entire server resources. For the sake of discussion, assume the system crashes if two instances of the C function are run simultaneously.
QUESTION: Is there a way I can make sure that at most only one instance of this function is ever allowed to run (simultaneously)?
That's what a mutex is for - to permit mutual exclusion. Only one instance/thread/process can lock a mutex. Other entities will fail when they try, and will continue to fail until the owner unlocks the mutex.
There are a variety of ways of doing it. For your purposes, I think the simple, old-fashioned technique of a lock file is probably as good as any and better than some. The function (or a wrapper for the function) will look to see if it can create a lock file. If it can, it goes ahead and runs, and then removes the lock file when it is done. If it can't create the file, it looks to see what the file contains - it should be a PID of the last process to run the function. If the PID still exists (check with kill(0, pid)), then you're not allowed to run. If the PID does not exist, then it died without cleaning up its lock file, and you should ... worry about whether there's another process also detecting that the PID is not there.

Determine if a process is running?

Is there an easy way to determine if a certain process is running?
I need to know if an instance of my program is running in the background, and if not fork and create the background process.
Normally the race-free way of doing this is:
Open a lock file / pid file for writing (but do not truncate it)
Attempt to take an exclusive lock on it (using fcntl or flock) without blocking
If that fails with EAGAIN, then the other process is already running.
The file descriptor should now be inherited by the daemon and left open for its lifetime
The advantage of doing this over simply storing a PID, is that if somebody reuses the PID, you won't get a false positive.
The biggest problem with storing the pid in the file is that a low-numbered pid used by a system start up daemon can get reused on a subsequent reboot by a different daemon. I have seen this happen.
This is usually done using pidfiles: a file in /var/run/[name].pid containing only the process ID returned by fork().
if pidfile exists:
exit()
else:
create pidfile
pid = start_background()
pidfile.write(pid)
On shutdown: remove pidfile
Linux software, by far and large does not care about the exclusivity of programs, only the resources they use. "Caring" is most often provided by the implementation (E.G. the infrastructure of the distro).
For instance, if you want to run a program, but that program locks up or turns zombie and you have no way to kill it, or it's running as a different user performing some other function. Why should the program care whether another copy of itself is running? Having it do so only seems like an unnecessary restriction.
If it's a process that opens a socket (like a TCP port), have the program fail if it can't open the socket. If it needs exclusive access to a file, have it fail if it can't get it. Support a PID file, but don't make it mandatory.
You'll see this methodology all over GNU software, which is part of what makes it so versatile.

Resources