Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

macos - Get full list of running processes (including those owned by root) with Swift

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...