1

I'm new to Swift so to learn I'm trying to create a command line toot, in the code I'm running a node server using Process. The problem here is that when I exit the program the node process is still running and I want to end it whenever I exit the program or when I'm about to exit the program.

import Foundation

let port = "3030"

let process = Process.launchedProcess(launchPath: "/usr/local/bin/node", arguments: ["/path/to/file/index.js"])
print(process.processIdentifier)

I found out how to get the PID of the process but I don't know how to kill it on exit or when I'm about to exit.

Edit

process.terminate() works, but the behavior I want is to keep the program running until it's killed manually (ctrl + c), killing the node process with it. I can keep the program running by using waitUntilExit(), however, using terminate() won't work if I use waitUntilExit().

corasan
  • 2,636
  • 3
  • 24
  • 41
  • If it's not responding to SIGTERM (i.e. `process.terminate()`), then it may depend on the node process itself. If the program ignores SIGTERM, then you either need to rework it to not do that, or use SIGKILL. As a rule, you'd rather SIGTERM when possible. – Rob Napier Jan 06 '19 at 19:37
  • Note that `Process.launchedProcess` was deprecated in 10.13 and replaced with `Process.run`. Probably doesn't matter here, but noteworthy. – Rob Napier Jan 06 '19 at 19:40
  • @RobNapier ah thank you for the note. I should have explained better, `process.terminate()` does work. Will edit the original post explaining better. – corasan Jan 06 '19 at 19:42

1 Answers1

0

As this answer suggests:

import Foundation

// Start the Node process...

signal(SIGINT, SIG_IGN)

let sigintSource = DispatchSource.makeSignalSource(signal: SIGINT, queue: .main)
sigintSource.setEventHandler {
    process.terminate() // Terminate the Node process
    exit(0)
}
sigintSource.resume()
Itai Steinherz
  • 777
  • 1
  • 9
  • 19