Wali Waqar
Wali Waqar

Reputation: 385

Have an Electron App detach itself from its parent Process in Linux

How do you have an Electron app detach itself from its parent process on Linux so that when it is launched from the terminal, the terminal proceeds as if the process exited (the next command can be entered etc). Launching Visual Studio Code from the terminal is one example of what I am trying to achieve.

Upvotes: 0

Views: 518

Answers (2)

leitning
leitning

Reputation: 1506

Create your own launcher, you can combine it with the CLI script from the other day.

This would make an assumption that if the IPC server is not running, then it will launch and detach your app. You will need to launch the IPC server immediately in your app and even then there will be a race condition but if you use the requestSingleInstanceLock you should be fine.

Here's the updated CLI script

#!/usr/bin/node
const net = require('net'),
  {spawn} = require('child_process'),
  APP_LOC = '/path/to/electron-app';

let args = process.argv;
args.shift(); // Drop /usr/bin/node 
args.shift(); // Drop script path

let line = args.join(' ');
net.connect('/tmp/my-app.sock',(conn)=>{
  conn.setEncoding('utf8');
  conn.on('data',(response)=>{
    console.log(response);
    process.exit(0);
  });
  conn.write(line+'\n');
}).on('error',(err)=>{
  if(err.code == 'ENOENT') {
    console.log('Attempting to launch application');
    const cp = spawn(APP_LOC, {
      detached: true,
      stdio:'ignore',
    }).on('error', (err) => {
      console.error(err);
      process.exit(2);
    }).on('spawn', () => {
      cp.unref();
      console.log('Application launched');
      process.exit(0);
    });
  }
  else {
    console.error(err);
    process.exit(1);
  }
});

Upvotes: 1

theUndying
theUndying

Reputation: 1744

Prefix your command with nohup. Example: nohup ping 8.8.8.8 -c 100 </dev/null &>/dev/null &. If you close your terminal, and check ps aux | grep ping from another, you'll see it's still running. Read more about nohup, disown and the ampersand (&) here

Some clarification on the above example: </dev/null is used to make every read call receive an EOF (effectively your application won't be stuck waiting for input), and &>/dev/null redirects stdin and stdout to /dev/null (as your application won't be writing anywhere, once it's detached from the controlling terminal). The & just runs the process in the background directly.

Upvotes: 1

Related Questions