kareman / SwiftShell

A Swift framework for shell scripting.
https://kareman.github.io/SwiftShell
MIT License
1.03k stars 87 forks source link

Cancel with Ctrl-C #77

Closed antranapp closed 5 years ago

antranapp commented 5 years ago

I have a list of long running bash commands that I execute using runAndPrint(bash: ) in a for loop. I try to terminate the execution using Ctrl-C but somehow the new command gets executed again. I assume that I can only terminate some of the subcommands but not the whole process. Any idea how can I listen for Ctrl-C in my code and cancel the whole process programmatically?

kareman commented 5 years ago

That's strange, I tried running this:

import SwiftShell

for i in 1 ... 5 {
    print(i)
    try runAndPrint(bash: "sleep 5")
}

and the entire application was terminated when I pressed Ctrl-C:

/tmp/cancel> swift run
[3/3] Linking cancel
1
2
^C
/tmp/cancel> 

Could you share the code in the for-loop?

antranapp commented 5 years ago

Ok strange, it seems that the application is really terminated and only the output is still buffered and printed out afterward.

Sorry for the confusion.

kareman commented 5 years ago

No problem. Just to be clear, I think what happens is that when you press CTRL-C the Swift application is terminated. The bash command that has already been launched will continue uninterrupted in its own separate process.

antranapp commented 5 years ago

@kareman thank you for your explanation. Do you have any idea how I can terminate also all subprocesses in this case?

kareman commented 5 years ago

I think you can do this to be notified when the user presses ctrl-c.

When running commands you need to use runAsync or runAsyncAndPrint and store it in a variable. So it can be cancelled later with .stop().

Let me know if it works, it would be nice to have the notification functionality in SwiftShell.

Ponyboy47 commented 5 years ago

I've used IBM's BlueSignals framework to do this in my own things.

They have an example here with how easy it is to trap on signals.