Processes in Node Part 2: Pid to Kill
Internally within node, every object has an id that V8 uses to keep track of these object. In the same way, when we invoke a request to the operating system to create a process, the operating system loads the program into memory and assigns it an id which can be used to track the running program throughout its life cycle.
The id this process is assigned is called a pid and it can be accessed from within node via process
Fun fact: if you open another terminal and type “kill -9 (process pid).” You will have effectivly terminated the process in the other window by having the operating system directly deliver a kill switch to your running node instance.
The process module is global so we don’t need to require it. It gives us alot of information about the running node instance that we can use in our programs.
Example operations include
- exiting the program
- changing directories/ getting directory information
- getting the name of the directory of the start script
- retrieving argumenst passed into the command line invocation of the script
specific to node.js is the ability to bind to occur at process events.
1 2 3 4 5 6 7 8 9 10
In the case of exit, the event loop terminates. The documentation specifically mentions events scheduled with setTimeout. Its important to note that this applies to all asych events as they all operate on setTimeout underneath.
Consequently, if you need to write some pertinent information to the disc, Be sure to use writeFileSync!!
TLDR: Processes can send signals to each other and recieve signals from the ernal
This isn’t limited to node processes speaking amongst themeselves. Ever run node and then exit it using ctrl-c.
For a great list of standard unix signals, check out this Awesome Chart
We can orginaize them according to their default behaviors.
- kill requests/reports
- error reporting
- device access notification
- coordinating io
We can overide the default behaviors for some of these signals.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
A more realistic scenario would be a situation in which you need to write some files to the disk before kicking off the exit procedures.
1 2 3 4 5
You cannot overwrite the kill -9 signal. This is why certain programs can become corrupted when you kill-9 them. they are not given a chance to save state.
For more information about signals, I found these two guides to be excellent.
Signals are a primitive pipeline for relaying messages. If you are looking to build some form of complex communication pipeline between individual processes, you are better off doing so over tcp. There are frameworks that facilitate this such as zeromq with an excellent node binding available.