Home > Software design >  Swift Run command line using processing(), but return "Error Domain=NSPOSIXErrorDomain Code=13
Swift Run command line using processing(), but return "Error Domain=NSPOSIXErrorDomain Code=13

Time:10-21

I am trying to run command lines in a macOS application after clicking a button. But when I run below codes, it always shows me this error "Domain=NSPOSIXErrorDomain Code=13 Permission denied". And, I have disabled the sandbox. Thank you for your help.

let command = "/Users/donghanhu/Documents/TestFolder"
var args = [String]()
args.append("ls")
let task = Process()
task.launchPath = command
task.arguments = args
do {
    try task.run()
} catch {
    print("something went wrong, error: \(error)")
}
task.waitUntilExit()

CodePudding user response:

I think you've misunderstood some features of how Process works. The documentation

A process operates within an environment defined by the current values for several items: the current directory, standard input, standard output, standard error, and the values of any environment variables. By default, an Process object inherits its environment from the process that launches it.

So the process will run within the current directory of the parent process. It looks like you are trying to change the current directory to

/Users/donghanhu/Documents/TestFolder

By using the launchPath of the Process, but launchPath should be set to the executable you want to run in the subprocess. In this case I think you want the launchProcess to be "/bin/ls" because you are trying to run an ls command.

So if you want a Process that will use ls to list the content of the folder /Users/donghanhu/Documents/TestFolder it would be:

import Foundation

let task = Process()
task.launchPath = "/bin/ls"
task.arguments = ["/Users/donghanhu/Documents/TestFolder"]
do {
    try task.run()
} catch {
    print("something went wrong, error: \(error)")
}
task.waitUntilExit()
  • Related