Kill process in swift
Asked Answered
L

2

0

I am trying to make a Mac application that will automatically close a code designated application running on the OS. I am trying to use killall (like in Terminal). Whenever I try to run the program, I get, "sysctl: unknown oid 'killall'".

Here's my code:

let task = Process()
    task.launchPath = "/usr/sbin/sysctl"
    ///usr/sbin/sysctl
    task.arguments = ["killall","iTunes"]
    let pipe = Pipe()
    task.standardOutput = pipe
    task.standardError = pipe
    task.launch()
    task.waitUntilExit()
    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    let output: String = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as! String
    print(output)

Thanks in advance!

Leprous answered 15/8, 2017 at 21:27 Comment(4)
You missed a forward slash. Shouldn't it be /usr/sbin/sysctl?Shipway
You are correct. But when I run it now, it states "sysctl: unknown oid 'killall". I have updated the question to this new error.Leprous
@CodeDifferent What sbin file do I need in order to use killall?Leprous
sysctl is not the one to use for that purpose.Glasser
S
2

I'd suggest you first read the man page for sysctl -- it's used to get and set kernel state. Does that sound like something you want?

The path to killall is /usr/bin/killall, which you can find from Terminal:

> which killall
/usr/bin/killall

Here's the full Swift code:

let pipe = Pipe()

let task = Process()
task.launchPath = "/usr/bin/killall"
task.arguments = ["iTunes"]
task.standardOutput = pipe
task.standardError = pipe
task.launch()
task.waitUntilExit()

let data = pipe.fileHandleForReading.readDataToEndOfFile()
if let output = String(data: data, encoding: .utf8) {
    print(output)
}
Shipway answered 15/8, 2017 at 22:50 Comment(0)
F
4

my 2 cents: You succeed in killing "iTunes" only if You Xcode App will run with SandoBox DISABLEDenter image description here

All examples on stack overflow about Process are misleading as they call "ls" or "echo" that are always executed in system folders.

Fess answered 21/10, 2018 at 6:19 Comment(0)
S
2

I'd suggest you first read the man page for sysctl -- it's used to get and set kernel state. Does that sound like something you want?

The path to killall is /usr/bin/killall, which you can find from Terminal:

> which killall
/usr/bin/killall

Here's the full Swift code:

let pipe = Pipe()

let task = Process()
task.launchPath = "/usr/bin/killall"
task.arguments = ["iTunes"]
task.standardOutput = pipe
task.standardError = pipe
task.launch()
task.waitUntilExit()

let data = pipe.fileHandleForReading.readDataToEndOfFile()
if let output = String(data: data, encoding: .utf8) {
    print(output)
}
Shipway answered 15/8, 2017 at 22:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.