Skip to content

Commit

Permalink
add control-c-handler to rsutils
Browse files Browse the repository at this point in the history
  • Loading branch information
maloel committed Jan 3, 2025
1 parent e52b990 commit 5f5b74a
Show file tree
Hide file tree
Showing 2 changed files with 100 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2024 Intel Corporation. All Rights Reserved.
#pragma once


namespace rsutils {
namespace concurrency {


// A Python Event-like implementation, simplifying condition-variable and mutex access
//
class control_c_handler
{
public:
control_c_handler();
~control_c_handler();

bool was_pressed() const;

void wait();
};


} // namespace concurrency
} // namespace rsutils
75 changes: 75 additions & 0 deletions third-party/rsutils/src/control-c-handler.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2024 Intel Corporation. All Rights Reserved.
#include <rsutils/concurrency/control-c-handler.h>
#include <rsutils/concurrency/event.h>
#include <rsutils/easylogging/easyloggingpp.h>

#include <signal.h>


namespace rsutils {
namespace concurrency {


namespace {

event sigint_ev;


void handle_signal( int signal )
{
switch( signal )
{
case SIGINT:
sigint_ev.set();
break;
}
}

} // namespace


control_c_handler::control_c_handler()
{
#ifdef _WIN32
signal( SIGINT, handle_signal );
#else
struct sigaction sa;
sa.sa_handler = &handle_signal;
sa.sa_flags = SA_RESTART;
sigfillset( &sa.sa_mask );
if( sigaction( SIGINT, &sa, NULL ) == -1 )
LOG_ERROR( "Cannot install SIGINT handler" );
#endif
}


control_c_handler::~control_c_handler()
{
#ifdef _WIN32
signal( SIGINT, SIG_DFL );
#else
struct sigaction sa;
sa.sa_handler = SIG_DFL;
sa.sa_flags = SA_RESTART;
sigfillset( &sa.sa_mask );
if( sigaction( SIGINT, &sa, NULL ) == -1 )
LOG_DEBUG( "cannot uninstall SIGINT handler" );
#endif
}


bool control_c_handler::was_pressed() const
{
return sigint_ev.is_set();
}


void control_c_handler::wait()
{
sigint_ev.clear_and_wait();
}


} // namespace concurrency
} // namespace rsutils

0 comments on commit 5f5b74a

Please sign in to comment.