rust-ctrlc icon indicating copy to clipboard operation
rust-ctrlc copied to clipboard

ctrlc::Counter

Open henninglive opened this issue 8 years ago • 3 comments

A common pattern when handling Ctrl+C is setting a flag in the handler and polling the flag somewhere else in the application. The current API does allow you to implement this, but there is significant extra overhead because the extra thread, pipes and semaphores. I think it would make sense to try and build a safe abstraction with less overhead for this use case.

I suggest implementing a new ctrlc::Counter abstraction as a struct. A ctrlc::Counter increases its value each time a specific signal is received. It will implement Send and Sync, allowing other threads poll and reset its value. Creating a new ctrlc::Counter registers a native signal handler. The lifetime of the native handler is connected to the ctrlc::Counter and will be unregistered when the ctrlc::Counter is dropped, this allows users unregister the handler if they want. We would probably also need to distinguish between SIGINT and SIGTERM, and possibly between CTRL+C and CTRL+BREAK. So, implementing a signal enum as suggested in #26 is probably a good idea.

I think using a counter is better than a simple flag, a counter can be used in all cases where you would use a flag, but the counter opens for additional use cases not covered by a simple flag.

The suggested abstraction is similar to the one provided by signalbool, a crate owned by @lilydjwg. I guess he created this after our discussion in #20.

I feel like this interface and the interface I suggested in #28 fits well with Rust’s philosophy of safe abstractions.

henninglive avatar Jun 19 '17 15:06 henninglive

I just got this implemented. It still needs some polishing so I'll put it up for a review later this week.

Detegr avatar Sep 18 '17 07:09 Detegr

Is this issue dead? This would be useful for me at the moment but there seems to be no way of doing this?

daniel-brenot-apcapital avatar Jul 29 '22 18:07 daniel-brenot-apcapital

I have a PR for this: https://github.com/Detegr/rust-ctrlc/pull/60

It's just that it will add so much (unsafe) complexity that no one has reviewed so I haven't had the courage to merge it.

Detegr avatar Jul 29 '22 19:07 Detegr

No one seems to be interested enough in reviewing my code in the pull request, which is completely understandable. It's been multiple years now so I'm thinking the counter+channel code will never be merged, so I'll close this and #28.

Detegr avatar May 20 '23 18:05 Detegr