I am running a for loop which opens up a different fork process on each go. Since I want to limit the total number of concurrent processes, I have a tally which increases by one every time a fork process is initiated, and which is supposed to decrease by one each time a fork process is completed. Unfortunately, my parent process is not receiving any indicator when a child process has completed. Here is my code for reference:
Parent process:
let maxChildren = 2000;
let numChildren = 0;
for (let i = 0; i < invoicesLen; i++){
let ran = false;
while (ran === false){
if (numChildren < maxChildren){
let child = fork(__dirname + `/stuff/index.js`)
numChildren += 1;
child.on('exit', () => {
// This code is not executing at any point
numChildren -= 1;
console.log('child closed')
console.log(`There are ${numChildren} child processes running`)
})
console.log(`There are ${numChildren} child processes running`)
ran = true;
}
}
}
And this is the child process:
(mainFunction = () => {
// Does stuff
console.log('exiting...')
process.exit();
})()
I get the 'exiting...' console log from the child process, but my function in child.on('exit' ... etc in the parent script does not get executed.