简体   繁体   中英

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

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.

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.

After some searching and a brief coffee break, I'm convinced that child_process.spawn is the way to go. Making an object array to handle the processes, and deleting those process objects on exit seems to work well.

See: https://gist.github.com/3990987

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM