How to catch error when setting launchpath in NSTask

后端 未结 3 1333
野的像风
野的像风 2021-01-18 02:58

I am trying to run a commandline tool using swift 2 on a mac (10.10):

let task = NSTask()
task.launchPath = \"/path/to/wrong/binary\"
task.launch()

// NSPip         


        
3条回答
  •  时光取名叫无心
    2021-01-18 03:36

    You're not supposed to catch it. Your computer, the local environment that you app is running in, is deemed as a reliable medium. Therefore, NSTask is designed to expect that any path you feed it is guaranteed to exist. This holds up fine as folks are usually using NSTask to launch standard system executables (bash, diff, rsync, etc...). The crash on an mistyped path is meant to help you find bugs in your code easily. If you're launching your own custom-built binaries embedded in the app's bundle, you should really be using XPC instead.

    If you absolutely need to use NSTask to launch unreliable paths, before you create your object, you need to validate the path manually using NSFileManager's fileExistsAtPath(_:isDirectory:) and react accordingly. If even the POSIX permissions flags are unreliable (at which point, your app likely has some serious security problems; if this is a consumer application project, I recommend you rethink your design), you'll also want to check the file's NSFilePosixPermissions attribute to make sure it's executable.

提交回复
热议问题