Run a terminal command in a Mac app with Swift Xcode

前端 未结 1 1561
半阙折子戏
半阙折子戏 2021-02-08 15:15

I am trying to run a terminal command in a Mac app that I am developing. The terminal command is:

sudo sysctl -w net.inet.tcp.delayed_ack=0

I h

1条回答
  •  既然无缘
    2021-02-08 15:57

    Try this and let me know if it works. You should do this on a background thread using dispatch_async or NSOperationQueue. For more information on how to do stuff using Grand Central Dispatch read my post: http://manavgabhawala.me/#/blog/grand-central-dispatch

    let task = NSTask()
    task.launchPath = "/usr/sbin/sysctl"
    task.arguments = ["-w", "net.inet.tcp.delayed_ack=0"]
    let pipe = NSPipe()
    task.standardOutput = pipe
    task.standardError = pipe
    task.launch()
    task.waitUntilExit()
    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    let output: String = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
    

    Also please can you update the question to include the exact error and the code you are using with NSTask if this doesn't work. Now this won't have the sudo effect that you wanted if you want that look at: https://developer.apple.com/library/mac/documentation/Security/Conceptual/authorization_concepts/01introduction/introduction.html which tells you about how to use sudo. For an unsandboxed app you could also do the same thing as above but change the launchPath to /bin/sh and then add an argument "-S" and also add the argument "/usr/sbin/sysctl". Then you can use standardInput to pipe in the password of the user who has root access. All password entry errors will come in the standard error pipe. Let me know if this works.

    0 讨论(0)
提交回复
热议问题