Search code examples
node.jslinuxmacoschild-process

pause child process from node.js


If I have a child process running from node.js

const k = cp.spawn('bash');

k.stdin.end(`do long process`);

k.stdout.pipe(process.stdout);
k.stderr.pipe(process.stderr);

I learned recently that using ctrl+z that I can stop/pause a process completely and then restart it by typing fg.

I think the same thing can be accomplished by using these signals:

`kill -STOP ${k.pid}`
`kill -CONT ${k.pid}`

how can I send these signals to the child process, to stop/restart the child process?


Solution

  • Alright I jumped the gun a bit here, this solves it just fine, using k.kill('SIGSTOP') and k.kill('SIGCONT'):

    #!/usr/bin/env node
    
    const cp = require('child_process');
    
    const k = cp.spawn('bash');
    
    k.stdin.end(`
       var=0;
       while true; do 
           var=$((var+1))
           echo "count: $var"
           sleep 0.01
       done;
    `);
    
    k.stdout.pipe(process.stdout);
    k.stderr.pipe(process.stderr);
    
    
    const pauseAndRestart = () => {
    
        setTimeout(() => {
            k.kill('SIGSTOP');
            setTimeout(() => {
                k.kill('SIGCONT');
                pauseAndRestart();
            },2000);
        }, 2000);
    
    };
    
    pauseAndRestart();
    

    this script will pause and restart the child process over and over. (Tested on MacOS only). I am not sure about the ramifications of pausing a process and how it might differ with Windows or Linux. Any insight there appreciated.