Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c++

c

linux

ipc

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.

like image 514
lvella Avatar asked Jan 17 '11 16:01

lvella


People also ask

Can two processes be associated with same program?

A computer program is a passive collection of instructions, a process is the actual execution of those instructions. Several processes may be associated with the same program; for example, opening up several instances of the same program often means more than one process is being executed.

Can two processes be concurrently executing the same program executable?

(a) Can two processes be concurrently executing the same program executable? (b) Can two running processes share the complete process image in physical memory (not just parts of it)? Ans: (a) Yes, two processes can run the same program.

Which is the correct relationship between programs and processes?

Program contains a set of instructions designed to complete a specific task. Process is an instance of an executing program.

Why do programs have multiple processes?

Loading and executing individual processes rather than the entire program makes a computer run much faster. Another advantage of executing individual processes is that if an individual process crashes, the rest of the program can continue to function. Thus, processes allow a computer to run more reliably.


1 Answers

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).

like image 108
Fred Foo Avatar answered Sep 20 '22 14:09

Fred Foo