Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js: Is there a way for the callback function of child_process.exec() to return the process PID

Tags:

node.js

exec

Node.JS Exec Question:

I have a program which spawns multiple processes, and I'd like to log the order of the processes finishing by capturing the PID when the process finishes. From what I can tell the standard callbacks do not include the PID (stdout,stderr,and error).

I'd like to avoid using spawn, but it looks like I'll have to, unless any kind souls have some ideas.

Thanks in advance.

EDIT:

To clarify:

var child = child_process.exec(..., function() {
    console.log( child.pid );
});

will not work for multiple processes. This returns the last process, not the process which triggered the call back.

like image 904
Dan Steingart Avatar asked Dec 03 '25 11:12

Dan Steingart


1 Answers

var child = child_process.exec(..., function() {
    console.log( child.pid );
});

I highly suggest reading the documentation - you might find answers to all your questions there. :)

// EDIT If you are using a loop to create processes, then use it like that:

var create_child = function( i ) {
    // creates a seperate scope for child variable
    var child = child_process.exec(..., function() {
        console.log( child.pid );
    });
};

for (var i = 0; i < 100; i++) {
    // does not create a seperate scope
    create_child( i );
}

to avoid scoping issues.

like image 88
freakish Avatar answered Dec 06 '25 08:12

freakish