0

I've been able to successfully run commands using the exec() command. However, I'd like to leave a process running and continue to run commands on the open process, then close on app exit. Take this generic code:

const { exec } = require("child_process");

exec("XR_Command -i 192.168.0.100 -f /ch/01/on | kill", (error, stdout, stderr) => {
    if (error) {
        console.log(`error: ${error.message}`);
        return;
    }
    if (stderr) {
        console.log(`stderr: ${stderr}`);
        return;
    }
    console.log(`stdout: ${stdout}`);
});

I would like to keep the XR_Command process active so that I can issue commands to the active process. So, basically I would like to do this:

> XR_Command -i 192.168.0.100

> /ch/01/on
> /ch/02/on
> /ch/03/on

I cannot for the life of me figure out how to make this function properly by referencing the existing child process. Thanks!

4
  • 2
    You'll need to use child_process.spawn() instead, so you can set the stdio configuration so you get a handle to the child process's input handle. Commented Aug 31, 2021 at 19:44
  • Okay, I'll give that a shot and see if I can figure that out. I'm aware of spawn() and have read about it a bit, we'll see if I can make that work. Thanks for the info. Commented Aug 31, 2021 at 20:01
  • @AKX I understand the spawn() and exec() functions when run a single time, but I just can't grasp how to run commands on the existing process. Any examples? Commented Aug 31, 2021 at 20:23
  • 2ality.com/2018/05/child-process-streams.html Commented Aug 31, 2021 at 22:21

1 Answer 1

2

Okay, so after a day I figured out two main problems I was running in to, here is my working code:

const { spawn } = require('child_process');

let Command = spawn('X_Control', ['-i', '192.168.0.1']);
Command.stdout.pipe(process.stdout);
Command.stderr.pipe(process.stderr);

Command.stdin.write('some command\n');

Command.on('error', function(err) {
    console.error(err);
});

Command.stderr.on('data', (data) => {
    console.log(`stderr: ${data}`);
});

Command.on('close', (code) => {
    console.log(`child process exited with code ${code}`);
});

Issue 1: My application command was X_Control -i 192.168.0.1, every space needs to be quoted separately as Command = spawn('X_Control', ['-i', '192.168.0.1']); This took me a while to track down.

Issue 2: Command.stdin.write('some command\n'); is how I execute commands on my running application, and it must be followed by \n in order to execute the command.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.