2

I am developing an app for monitoring the highest consuming processes in Swift, but I'm stuck at the part of obtaining the list of processes that are currently running. I've tried a lot of things, such as:

  1. Running the top or ps aux | less commands and parsing the output.

I tried using this code to run the top command and pass the output to a NSPipe in order to parse it later, but I can't seem to run the command because it gives the error Couldn't posix_spawn: error 13, and I couldn't find anything on the internet on how to fix this, so I had to find another way.

let task = Process()
let pipe = Pipe()

task.standardOutput = pipe
task.launchPath = "/usr/bin"
task.arguments = ["top"]
task.launch()
task.waitUntilExit()

let data = String(data: pipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8)!
  1. Using NSWorkspace.shared.runningApplications

I saw this stack overflow question regarding the same topic, but it isn't answered (one comment references another thread that answers how to do it in C, but it isn't what I actually expected). The thread's OP used the code below in order to get the full list of running processes, but it only returns the user-owned ones, so it isn't really useful.

let workspace = NSWorkspace.shared
let applications = workspace.runningApplications        

for application in applications {

    if let url = (application.executableURL?.absoluteString) {

            os_log("%{public}s", log:scribe, type:.debug, url)
        }
    }
}

Conclusion

Is there a way I can get a list of running processes in macOS (including those owned by root) in Swift? If there's another way through which I could retrieve at least the two most CPU-consuming processes that would do as well.

Thanks in advance.

amodrono
  • 1,900
  • 4
  • 24
  • 45
  • 1
    This error occurs as well with other task who will get some kind of "non stop output" and not a "on time output". Disabling the sandbox sometimes fixes those issues, but often you will get the error message "stdin is no terminal". The smother way to run those tasks is to write a small shell script or embed a terminal emulator like SwiftTerm or something like this. – DoTryCatch Jan 14 '21 at 21:19
  • 1
    @amodrono you found any solution? i looking how to get a process by name like `pgrep "Google Chrome Helper \(GPU\)"` and i like to do something like `pkill -f "Google Chrome Helper \(GPU\)"` - but at first i can not get the pid :( – muescha Sep 24 '22 at 03:27

0 Answers0