How to get the pid of forked child process NODE JS - node.js

I'm forking child process in node and my business logic requires me to call this fork process again and again.Issue is to clean up previous forked process before calling next one.Is there any way that i can get my forked process pid ,so we can store it and kill it on next run
const program = path.join(__dirname, 'test.js');
var myProgram= fork.fork(program, [], {
silent: true
});

fork will retrun a ChildProcess object. This object contains a bunch of properties including pid and kill.
You can use the kill method to conveniently 'kill' your subprocess
const forked = child_process.fork("path");
forked.pid // 189...
forked.killed // false
forked.kill();
forked.killed // true

Related

Child Process Output Not Shown in Node.JS

I am executing below code in NodeJS.
As seen below parent process spawns a child process and sets env variable.
This variable is used to decide if process is parent or child when executing the file.
const {IS_CHILD} = process.env
if(IS_CHILD){
console.log('CHILD');
console.log('child pid = ',process.pid);
console.log('child env values = ',process.env);
}else{
const {parse} = require('path')
const {root} = parse(process.cwd());
console.log('PARENT');
console.log('parent pid = ',process.pid)
const {spawn} = require('child_process');
const sp = spawn(process.execPath,[__filename], {
cwd: root,
env: {IS_CHILD : true}
});
sp.stdout.pipe(process.stdout); // if this is commented
}
The issue I am facing is , if I comment out code sp.stdout.pipe(process.stdout) inside parent process , the child process output is not shown on console.
(Three lines inside IS_CHILD if block )
If sp.stdout.pipe(process.stdout) line is commented out , does that mean that process.env for child process is also not written ?
Can anybody please help here ?
Am I missing anything here ?
I was assuming that even if sp.stdout.pipe(process.stdout) line is commented out , the child process should have env variable set in it as we have executed spawn command
If sp.stdout.pipe(process.stdout) line is commented out , does that mean that process.env for child process is also not written ?
No. Environment variable is still there.
Explanation
The output you get is expected.
When you run your script, it starts parent process. So what you will see in the console is output of parent process. Then, via spawn you are spawning a child process. The child process is a completely different process. In order to see its output in the parent process, you can use piping as you do.
Another option is to use events of child process. You can attach a handler to child process' stdout data event. e.g
sp.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
For more info about child processes, see child process reference.
If you omit piping, the child process will write output to its own stdout which is different from parent process' stdout. Therefore, you don't see it.

Node.js Change stdio of already running child process (to unref it)

I trying to figure out how to do the code below, but after a process has already been launched:
const { spawn } = require('child_process')
const subprocess = spawn('top', {
stdio: 'ignore'
})
subprocess.unref()
The reason is I'm using a library that launches a child process (puppeteer), and they do give access to the child process created, so I can use .unref() but I can't pass the stdio: 'ignore' options, which seems to be necessary in order to unref and have the node program exit after it is finished.

Sending message from child process to parent process when creating child_process with exec()

I have a parent process in Node.JS which creates a child process through calling exec.
I want to wait until the child process finish and return the status of the child process.
I don't want to use spawn or fork.
I'm creating the child_process with require('child_process').exec
I need the child process to send message to the parent process through IPC:
function foo()
{
const exec = require('child_process').exec;
const cmd = `cd /usr/lib/bin' && db-migrate --config "config/${environmentName}.json" -e ${environmentName} -v true up --force-exit`;
const child = exec(cmd, (error, stdout, stderr) => {
//...
});
child.on('exit', (code) => {
//from here i want to know if there was a problem in child process
//can I use IPC to send messages?
});
//wants to return the child status code from here
return child_status_code;
}
How can i solve this problem?
How can I use IPC from child process to parent process?
If there is a IPC channel created in process, you are able to send message from child to parent by "process.send“. It is addressed in documentation of Nodejs.
The IPC channel is only available by "fork". "fork" has the first parameter is module path.

Node child process can not run detached

I'm trying to fork a node child process with
child_process.fork("child.js")
and have it say alive after the parent exits. I've tried using the detached option like so:
child_process.fork("child.js", [], {detached:true});
Which works when using spawn, but when detached is true using fork it just fails silently, not even executing the child.js.
I've also tried
var p = child_process.fork("child.js")
p.disconnect();
p.unref();
But child still dies when the parent does.
Any help or insight would be greatly appreciated.
EDIT:
Node Version: v5.3.0
Platform: Windows 8.1
Code:
//Parent
var child_process = require("child_process");
var p;
try{
console.log(1)
p = child_process.fork("./child.js")
console.log(2)
} catch(e){
console.log(e)
}
p.on('error', console.log.bind(console))
p.disconnect();
p.unref();
//To keep process alive
setTimeout(() => {
console.log(1);
}, 100000);
--
//Child
var fs = require("fs");
console.log(3);
fs.writeFileSync("test.txt", new Date().toString());
setTimeout(()=>{
console.log(1);
}, 100000);
I'm assuming you're executing your parent file from the command line, which is probably why it "appears" that the forked child is not executing. In reality when the parent process exits, the terminal stops waiting and thus prints a new line, waiting for your next command. This makes it seem like the child isn't executing, but trust me it is. Also there is no "detached" option for child_process.fork
Add some console.log() statements to your child process and you should see input printing in your terminal even after the parent has exited. If you don't it's because your child is prematurely exiting due to an error. Run your child process directly to debug it, before calling it from the parent.
Check out this quick example:
Hope this helps.

Node.JS Parent Process ID

Is it possible to get the parent process-id using Node.JS? I would like to detect if the parent is killed or fails in such a way that it cannot notify the child. If this happens, the parent process id of the child should become 1.
This would be preferable to requiring the parent to periodically send a keep-alive signal and also preferable to running the ps command.
You can use pid-file. Something like that
var util = require('util'),
fs = require('fs'),
pidfile = '/var/run/nodemaster.pid';
try {
var pid = fs.readFileSync(pidfile);
//REPLACE with your signal or use another method to check process existence :)
process.kill(pid, 'SIGUSR2');
util.puts('Master already running');
process.exit(1);
} catch (e) {
fs.writeFileSync(pidfile, process.pid.toString(), 'ascii');
}
//run your childs here
Also you can send pid as argument in spawn() call
I start Node.JS from within a native OSX application as a background worker. To make node.js exit when the parent process which consumes node.js stdout dies/exits, I do the following:
// Watch parent exit when it dies
process.stdout.resume();
process.stdout.on('end', function() {
 process.exit();
});
Easy like that, but I'm not exactly sure if it's what you've been asking for ;-)

Resources