Processes Have Names
Unix processes have very few inherent ways of communicating about their state.
Programmers have worked around this and invented things like logfiles. Logfiles allow processes to communicate anything they want about their state by writing to the filesystem, but this operates at the level of the filesystem rather than being inherent to the process itself.
Similarly, processes can use the network to open sockets and communicate with other processes. But again, that operates at a different level than the process itself, since it relies on the network.
There are two mechanisms that operate at the level of the process itself that can be used to communicate information. One is the process name, the other is exit codes.
Naming Processes
Every process on the system has a name. For example, when you start up an irb
session that process is given the name ‘irb’. The neat thing about process names is that they can be changed at runtime and used as a method of communication.
In Ruby you can access the name of the current process in the $PROGRAM_NAME
variable. Similarly, you can assign a value to that global variable to change the name of the current process.
puts $PROGRAM_NAME
10.downto(1) do |num|
$PROGRAM_NAME = "Process: #{num}"
puts $PROGRAM_NAME
end
outputs:
irb
Process: 10
Process: 9
Process: 8
Process: 7
Process: 6
Process: 5
Process: 4
Process: 3
Process: 2
Process: 1
As a fun exercise you can start an irb
session, print the pid, and change the process name. Then you can use the ps(1) utility to see your changes reflected on the system.
Unfortunately this global variable (and its mirror $0
) is the only mechanism provided by Ruby for this feature. There is not a more intent-revealing way to change the name of the current process.
In the Real World
To see an example of how this is used in a real project read through How Resque Manages Processes in the appendices.