xcode 6 swift system() command

后端 未结 1 1039
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-13 02:50

Is there a good description of swift system command? For example, this code

    let x = system(\"ls -l `which which`\")
    println(x)

pro

相关标签:
1条回答
  • 2021-01-13 03:13

    system() is not a Swift command but a BSD library function. You get the documentation with "man system" in a Terminal Window:

    The system() function hands the argument command to the command interpreter sh(1). The calling process waits for the shell to finish executing the command, ignoring SIGINT and SIGQUIT, and blocking SIGCHLD.

    The output of the "ls" command is just written to the standard output and not to any Swift variable.

    If you need more control then you have to use NSTask from the Foundation framework. Here is a simple example:

    let task = NSTask()
    task.launchPath = "/bin/sh"
    task.arguments = ["-c", "ls -l `which which`"]
    
    let pipe = NSPipe()
    task.standardOutput = pipe
    task.launch()
    
    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    if let output = NSString(data: data, encoding: NSUTF8StringEncoding) {
        println(output)
    }
    
    task.waitUntilExit()
    let status = task.terminationStatus
    println(status)
    

    Executing the command via the shell "/bin/sh -c command ..." is necessary here because of the "back tick" argument. Generally, it is better to invoke the commands directly, for example:

    task.launchPath = "/bin/ls"
    task.arguments = ["-l", "/tmp"]
    
    0 讨论(0)
提交回复
热议问题