简体   繁体   中英

Launch Command Line Tool as detached Process

Invoking a command line tool ( bash , ls ) via Process works, but unfortunately it is created as a child process.

I need to start the tool as a separate process, without adding it as a subprocess to my running application.

Therefore I tried to start a detached process of bash using launch services with

let ws = NSWorkspace.shared
let url = URL(fileURLWithPath: "/bin/bash")

let app = try ws.launchApplication(at: url, options: [.default], configuration: [
    .arguments: args,
    .environment: env
])

Unfortunately the call doesn't seem to do anything, I guess it only supports app bundles? How do I start a process, like eg bash , without creating a child process?

What I basically try to do is create a short-lived process that executes one thing and exits immediately without having my app as a parent.

One method would be to create a helper tool that fork s, starts a new session with setsid and invokes the command, but I'd prefer not to rely on an external tool, and forking my own process is out of the question. It is crucial that the invocation is done from a process with ppid=1 .

First of all, you can't create a process that isn't a child process. The only process that's not a child process is the bootstrap kernel process (PID 0). Every other process is a child of some other process.

You can accomplish this by starting the executable running using a Process object (formerly NSTask ) (the easy way) or with one of the traditional UNIX functions ( execle() et. al.), and then just let it run.

The only thing you have to do is make sure your child process isn't tied to anything that would cause it to block or stop when your application terminates. Most notably, connect stdin , stdout , and stderr to nothing (see NSFileHandle.fileHandleWithNullDevice ) or something like a file or pipe that is not controlled by your process.

Start the executable ( task.lanch() ) and then simply discard the Process object; it will continue running on its own.

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