How do I get Process object in Swift to direct sysout to a specific file on my Mac?

This should be simple, but I can't find useful documentation or examples.

in launchd, I can direct ouput where I want it. No problem.

Now, I want my app to launch a fresh copy of itself using Process. Just need to set standardOutput and standardError correctly. I know that 2nd instance is running & completing accurately, just can't figure out how to direct the output.

Can anyone help with this ?

Replies

Here is what I'm using to run docker commands and get stdout. You can repeat the same procedure with stderr. I use this for testing so I can wipe the test database between each test.


  func runDocker(arguments: [String]) throws -> String {
  #if os(Linux)
  let defaultDockerPath = "/usr/bin/docker"
  #else
  let defaultDockerPath = "/usr/local/bin/docker"
  #endif
  if nil == dockerURL {
  let envPath = ProcessInfo.processInfo.environment["DOCKER_EXE"] ?? defaultDockerPath
  dockerURL = URL(fileURLWithPath: envPath)
  }
  let proc = Process()
  proc.executableURL = dockerURL
  proc.arguments = arguments
  let outPipe = Pipe()
  proc.standardOutput = outPipe
  do {
  try proc.run()
  proc.waitUntilExit()
  guard proc.terminationStatus == 0 else { 
  logger.error("docker exec returned \(proc.terminationStatus)")
  throw Rc2TestErrors.noneZeroExitStatus 
  }
  let outputData = outPipe.fileHandleForReading.readDataToEndOfFile()
  return String(decoding: outputData, as: UTF8.self)
  } catch {
  logger.critical("error '\(error)' trying to exec docker \(arguments.joined(separator: " "))")
  throw Rc2TestErrors.dockerCommandFailed
  }
  }

Can you provide moer details about the context in which your code is running. You wrote:

in

launchd
, I can direct ouput where I want it. No problem.

Now, I want my app to launch a fresh copy of itself using Process.

Is your app a GUI app that users double click from the Finder. Or are you using app in a more general sense?

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"