linux c++ libev official example show redundant console behavior - c++

I just tried the official example of libev, like below. After compiling and running, I see once I input anything from stdin, the event is triggered, no problem. But what I inputed is still treated as solid input and then appear on my console. My question is: is there a way to avoid this console input from being prompted to console, and just like libev to catch and store it?
Any way in libev can do this?
I paste the official example here:
// a single header file is required
#include <ev.h>
#include <stdio.h> // for puts
// every watcher type has its own typedef'd struct
// with the name ev_TYPE
ev_io stdin_watcher;
ev_timer timeout_watcher;
// all watcher callbacks have a similar signature
// this callback is called when data is readable on stdin
static void
stdin_cb (EV_P_ ev_io *w, int revents)
{
puts ("stdin ready");
// for one-shot events, one must manually stop the watcher
// with its corresponding stop function.
ev_io_stop (EV_A_ w);
// this causes all nested ev_run's to stop iterating
ev_break (EV_A_ EVBREAK_ALL);
}
// another callback, this time for a time-out
static void
timeout_cb (EV_P_ ev_timer *w, int revents)
{
puts ("timeout");
// this causes the innermost ev_run to stop iterating
ev_break (EV_A_ EVBREAK_ONE);
}
int
main (void)
{
// use the default event loop unless you have special needs
struct ev_loop *loop = EV_DEFAULT;
// initialise an io watcher, then start it
// this one will watch for stdin to become readable
ev_io_init (&stdin_watcher, stdin_cb, /*STDIN_FILENO*/ 0, EV_READ);
ev_io_start (loop, &stdin_watcher);
// initialise a timer watcher, then start it
// simple non-repeating 5.5 second timeout
ev_timer_init (&timeout_watcher, timeout_cb, 5.5, 0.);
ev_timer_start (loop, &timeout_watcher);
// now wait for events to arrive
ev_run (loop, 0);
// break was called, so exit
return 0;
}

I assume you mean the echoing of what you write? It's the default behavior of terminal program. You can use termios functions and flags to disable echoing. Remember to enable it before exiting your program though.

In ev_io_init you are setting what your trigger will be. Instead of setting STDIN_FILENO you can choose to use a fd from a socket for example. Don't know if this is what you are looking for. Here you have an example of what I am saying.

Related

C++ Interrupting UDP Listener. Compiled using oscpack in Xcode

I have successfully incorporated an UDPreceive function into my application. HOWEVER! I can not figure out how to stop UDP listener from running infinitely. The OSCPack library has a Break() and AsynchronousBreak() built into it, but I have been unable to implement these.
in the udpSocket.cpp file within oscpack:
void Run() //the listener function (WORKING!)
{
break_ = false;
//UDP Listener Code
void Break()
{
break_ = true;
}
void AsynchronousBreak()
{
break_ = true;
// Send a termination message to the asynchronous break pipe, so select() will return
write( breakPipe_[1], "!", 1 );
}
}
My attempt to call Break() from the packet Listener class doesn't appear to do anything, despite the compiler suggesting that everything is being called correctly:
SocketReceiveMultiplexer s;
s.Break();
Another method that I have tried was to raise an interrupt flag in accordance with the RunUntilSigInt() function. Within the packet listener class:
raise(SIGINT);
but this terminates the whole program, rather than just breaking from the UDPListener. For reference, here is the RunUntilSigInt() code within udpSocket.cpp:
void SocketReceiveMultiplexer::RunUntilSigInt()
{
assert( multiplexerInstanceToAbortWithSigInt_ == 0 ); /* at present we support only one multiplexer instance running until sig int */
multiplexerInstanceToAbortWithSigInt_ = this;
signal( SIGINT, InterruptSignalHandler );
impl_->Run();
signal( SIGINT, SIG_DFL );
multiplexerInstanceToAbortWithSigInt_ = 0;
}
I'm completely stuck on this one, any help/advice will be greatly appreciated.
Thanks,
Tom
I know this is a somewhat old question, but I had to overcome this recently and didn't find a good answer online. The model used by oscpack seems to be that they control the infinite Run loop, and you implement everything you want to do inside a class derived from OscPacketListener. If you don't want to do things that way, you need to run the Run loop in a separate thread. It seems in the oscpack 1.1.0 release, there is no internal support for threading anymore. They explain in the CHANGES file for that release that you would need to implement your own threading solution. The Run routine in SocketReceiveMultiplexer never returns, so any code after that call is unreachable. The various Break routines are for controlling the execution of the Run loop from a different thread. In the below example I'm using c++11 <threads> but you can use any threading library you choose to accomplish something similar. In my example, you'll have to
#include <threads>
#include <mutex>
and compile your code with a c++11 compatible compiler. In g++ you would need the -std=c++11 command line argument.
If you start with the receiver example (parsing single messages example) in the SVN, you could change the main() function to be something like
void ListnerThread()
{
PacketListener listener;
UdpListeningReceiveSocket s(
IpEndpointName( IpEndpointName::ANY_ADDRESS, PORT ),
&listener );
s.Run();
}
Somewhere else in your code, make a call like
std::thread lt(ListnerThread);
in order to start the listener running. You'll have to create some means of sharing information between your main thread and the listener thread. One simple method is to use a global variable surrounded by a mutex (also global). There are certainly other (better?) ways but this is very easy. Declare these globally (following their example) instead of within the ProcessMessage function:
std::mutex oscMutex;
bool a1;
osc::int32 a2;
float a3;
const char *a4;
Inside the ExamplePacketListener, where they set the variables from the args stream and then make a call to cout you would do something like
oscMutex.lock();
args >> a1 >> a2 >> a3 >> a4 >> osc::EndMessage;
oscMutex.unlock();
Just be sure to also lock() and unlock() the mutex in the same way wherever you access those variables elsewhere in your code.
This is old, but this is the only page on the web about this issue. In case someone needs oit
Using raise(SIGINT) when i run the listener with RunUntilSigInt() function does the trick for me. It's a quick hack and it is ugly but it goes like this:
if (std::strcmp(m.AddressPattern(), "/test1") == 0) {
osc::ReceivedMessageArgumentStream args = m.ArgumentStream();
osc::int32 a1, a2, a3;
const char *a4;
args >> a1 >> a2 >> a3 >> a4 >> osc::EndMessage;
raise(SIGINT);
}
In this case, i stop the listener when i receive one pack, but you can modify it as you wish.
Sorry for stupid question: did you try to run the listener before the breaking?
SocketReceiveMultiplexer s;
s.Run(); // let wire up the things
s.Break();

How can I make poll() exit immediately in C on Linux?

I'm using the function poll() (I think it might be part of POSIX?) C function in my C++ class in order to get an event when a file changes. This seems to work just fine - but now I also want to be able to cause the function to exit immediately when I need to close the thread.
I researched this and came up with a couple of ideas that I tried - like trying to send a signal, but I couldn't figure out how to get this to work.
In the code below (which isn't 100% complete, but should have enough to illustrate the problem), I have a C++ class that starts a thread from the constructor and wants to clean up that thread in the destructor. The thread calls poll() which returns when the file changes, and then it informs the delegate object. The monitoring thread loops until the FileMonitor object indicates it can quit (using a method that returns a bool).
In the destructor, what I would like to do is flip the bool, then do something that causes poll() to exit immediately, and then call *pthread_join()*. So, any ideas on how I can make poll() exit immediately?
This code is targeted towards Linux (specifically debian), but I'm also working on it on a Mac. Ideally it the poll() API should work basically the same.
void * manage_fm(void *arg)
{
FileMonitor * theFileMonitor = (FileMonitor*)arg;
FileMonitorDelegate * delegate;
unsigned char c;
int fd = open(theFileMonitor->filepath2monitor(), O_RDWR);
int count;
ioctl(fd, FIONREAD, &count);
for (int i=0;i<count;++i) {
read(fd, &c, 1);
}
struct pollfd poller;
poller.fd = fd;
poller.events = POLLPRI;
while (theFileMonitor->continue_managing_thread()) {
delegate = theFileMonitor->delegate;
if (poll(&poller, 1, -1) > 0) {
(void) read(fd, &c, 1);
if (delegate) {
delegate->fileChanged();
}
}
}
}
FileMonitor::FileMonitor( )
{
pthread_mutex_init(&mon_mutex, NULL);
manage_thread = true;
pthread_mutex_lock (&mon_mutex);
pthread_create(&thread_id, NULL, manage_fm, this);
pthread_mutex_unlock(&pin_mutex);
}
FileMonitor::~FileMonitor()
{
manage_thread = false;
// I would like to do something here to force the "poll" function to return immediately.
pthread_join(thread_id, NULL);
}
bool FileMonitor::continue_managing_thread()
{
return manage_thread;
}
const char * FileMonitor::filepath2monitor()
{
return "/some/example/file";
}
Add a pipe to your file monitor class and switch your poll to take both your original file descriptor and the pipe's read descriptor to poll on. When you want to wake up your file monitor class for it to check for exit, send a byte through the pipe's write descriptor, that will wake up your thread.
If you have a large number of these file monitors, there's the possibility you could hit the maximum number of file descriptors for a process (See Check the open FD limit for a given process in Linux for details, on my system it's 1024 soft, 4096 hard). You could have multiple monitor classes share a single pipe if you don't mind them all waking up at once to check their exit indicator.
You should use a pthread condition variable inside (and just before) the poll-ing loop, and have the other thread calling pthread_cond_signal
You might consider the pipe(7) to self trick (e.g. have one thread write(2) a byte -perhaps just before pthread_cond_signal- to a pipe poll(2)-ed by another thread who would read(2) the same pipe). See also signal-safety(7) and calling Qt functions from Unix signal handlers. Both could inspire you.
With that pipe-to-self trick, assuming you do poll for reading that pipe, the poll will return. Of course some other thread would have done a write on the same pipe before.
See also Philippe Chaintreuil's answer, he suggests a similar idea.

set flag in signal handler

In C++11, what is the safest (and perferrably most efficient) way to execute unsafe code on a signal being caught, given a type of request-loop (as part of a web request loop)? For example, on catching a SIGUSR1 from a linux command line: kill -30 <process pid>
It is acceptable for the 'unsafe code' to be run on the next request being fired, and no information is lost if the signal is fired multiple times before the unsafe code is run.
For example, my current code is:
static bool globalFlag = false;
void signalHandler(int sig_num, siginfo_t * info, void * context) {
globalFlag = true;
}
void doUnsafeThings() {
// thigns like std::vector push_back, new char[1024], set global vars, etc.
}
void doRegularThings() {
// read filesystem, read global variables, etc.
}
void main(void) {
// set up signal handler (for SIGUSR1) ...
struct sigaction sigact;
sigact.sa_sigaction = onSyncSignal;
sigact.sa_flags = SA_RESTART | SA_SIGINFO;
sigaction(SIGUSR1, &sigact, (struct sigaction *)NULL);
// main loop ...
while(acceptMoreRequests()) { // blocks until new request received
if (globalFlag) {
globalFlag = false;
doUnsafeThings();
}
doRegularThings();
}
}
where I know there could be problems in the main loop testing+setting the globalFlag boolean.
Edit: The if (globalFlag) test will be run in a fairly tight loop, and an 'occasional' false negative is acceptable. However, I suspect there's no optimisation over Basile Starynkevitch's solution anyway?
You should declare your flag
static volatile sig_atomic_t globalFlag = 0;
See e.g. sig_atomic_t, this question and don't forget the volatile qualifier. (It may have been spelled sigatomic_t for C).
On Linux (specifically) you could use signalfd(2) to get a filedescriptor for the signal, and that fd can be poll(2)-ed by your event loop.
Some event loop libraries (libevent, libev ...) know how to handle signals.
And there is also the trick of setting up a pipe (see pipe(2) and pipe(7) for more) at initialization, and just write(2)-ing some byte on it in the signal handler. The event loop would poll and read that pipe. Such a trick is recommended by Qt.
Read also signal(7) and signal-safety(7) (it explains what are the limited set of functions or syscalls usable inside a signal handler)....
BTW, correctness is more important than efficiency. In general, you get few signals (e.g. most programs get a signal once every second at most, not every millisecond).

c++ winapi threads

These days I'm trying to learn more things about threads in windows. I thought about making this practical application:
Let's say there are several threads started when a button "Start" is pressed. Assume these threads are intensive (they keep running / have always something to work on).
This app would also have a "Stop" button. When this button is pressed all the threads should close in a nice way: free resources and abandon work and return the state they were before the "Start" button was pressed.
Another request of the app is that the functions runned by the threads shouldn't contain any instruction checking if the "Stop" button was pressed. The function running in the thread shouldn't care about the stop button.
Language: C++
OS: Windows
Problems:
WrapperFunc(function, param)
{
// what to write here ?
// if i write this:
function(param);
// i cannot stop the function from executing
}
How should I construct the wrapper function so that I can stop the thread properly?
( without using TerminateThread or some other functions )
What if the programmer allocates some memory dynamically? How can I free it before closing
the thread?( note that when I press "Stop button" the thread is still processing data)
I though about overloading the new operator or just imposing the usage of a predefined
function to be used when allocating memory dynamically. This, however, means
that the programmer who uses this api is constrained and it's not what I want.
Thank you
Edit: Skeleton to describe the functionality I'd like to achieve.
struct wrapper_data
{
void* (*function)(LPVOID);
LPVOID *params;
};
/*
this function should make sure that the threads stop properly
( free memory allocated dynamically etc )
*/
void* WrapperFunc(LPVOID *arg)
{
wrapper_data *data = (wrapper_data*) arg;
// what to write here ?
// if i write this:
data->function(data->params);
// i cannot stop the function from executing
delete data;
}
// will have exactly the same arguments as CreateThread
MyCreateThread(..., function, params, ...)
{
// this should create a thread that runs the wrapper function
wrapper_data *data = new wrapper_data;
data->function = function;
data->params = params;
CreateThread(..., WrapperFunc, (LPVOID) wrapper_data, ...);
}
thread_function(LPVOID *data)
{
while(1)
{
//do stuff
}
}
// as you can see I want it to be completely invisible
// to the programmer who uses this
MyCreateThread(..., thread_function, (LPVOID) params,...);
One solution is to have some kind of signal that tells the threads to stop working. Often this can be a global boolean variable that is normally false but when set to true it tells the threads to stop. As for the cleaning up, do it when the threads main loop is done before returning from the thread.
I.e. something like this:
volatile bool gStopThreads = false; // Defaults to false, threads should not stop
void thread_function()
{
while (!gStopThreads)
{
// Do some stuff
}
// All processing done, clean up after my self here
}
As for the cleaning up bit, if you keep the data inside a struct or a class, you can forcibly kill them from outside the threads and just either delete the instances if you allocated them dynamically or let the system handle it if created e.g. on the stack or as global objects. Of course, all data your thread allocates (including files, sockets etc.) must be placed in this structure or class.
A way of keeping the stopping functionality in the wrapper, is to have the actual main loop in the wrapper, together with the check for the stop-signal. Then in the main loop just call a doStuff-like function that does the actual processing. However, if it contains operations that might take time, you end up with the first problem again.
See my answer to this similar question:
How do I guarantee fast shutdown of my win32 app?
Basically, you can use QueueUserAPC to queue a proc which throws an exception. The exception should bubble all the way up to a 'catch' in your thread proc.
As long as any libraries you're using are reasonably exception-aware and use RAII, this works remarkably well. I haven't successfully got this working with boost::threads however, as it's doesn't put suspended threads into an alertable wait state, so QueueUserAPC can't wake them.
If you don't want the "programmer" of the function that the thread will execute deal with the "stop" event, make the thread execute a function of "you" that deals with the "stop" event and when that event isn't signaled executes the "programmer" function...
In other words the "while(!event)" will be in a function that calls the "job" function.
Code Sample.
typedef void (*JobFunction)(LPVOID params); // The prototype of the function to execute inside the thread
struct structFunctionParams
{
int iCounter;
structFunctionParams()
{
iCounter = 0;
}
};
struct structJobParams
{
bool bStop;
JobFunction pFunction;
LPVOID pFunctionParams;
structJobParams()
{
bStop = false;
pFunction = NULL;
pFunctionParams = NULL;
}
};
DWORD WINAPI ThreadProcessJob(IN LPVOID pParams)
{
structJobParams* pJobParams = (structJobParams*)pParams;
while(!pJobParams->bStop)
{
// Execute the "programmer" function
pJobParams->pFunction(pJobParams->pFunctionParams);
}
return 0;
}
void ThreadFunction(LPVOID pParams)
{
// Do Something....
((structFunctionParams*)pParams)->iCounter ++;
}
int _tmain(int argc, _TCHAR* argv[])
{
structFunctionParams stFunctionParams;
structJobParams stJobParams;
stJobParams.pFunction = &ThreadFunction;
stJobParams.pFunctionParams = &stFunctionParams;
DWORD dwIdThread = 0;
HANDLE hThread = CreateThread(
NULL,
0,
ThreadProcessJob,
(LPVOID) &stJobParams, 0, &dwIdThread);
if(hThread)
{
// Give it 5 seconds to work
Sleep(5000);
stJobParams.bStop = true; // Signal to Stop
WaitForSingleObject(hThread, INFINITE); // Wait to finish
CloseHandle(hThread);
}
}

SIGINT signal()/sigaction in C++

So here is my code:
void sigHandle(int sig)
{
signal(SIGINT, sigHandle); //Is this line necessairy?
cout<<"Signal: "<<sig<<endl;
}
int main(){
signal(SIGINT, sigHandle);
while(true){ //Supposed to loop until user exits.
//rest of my code
}
}
Now it is my understanding of signal() that when the SIGINT command (Ctrl+C right?) is received my function sigHandle should be called with an integer value of 2 (the SIGINT number), the method should run and the program should NOT exit.
All I would like to do is just print the signal number and move on, however after printing out "Signal: 2" it exits.
(Eventually I'm supposed to handle the first 32 interrupts but I figured Ctrl+C would be the most difficult so I'm starting here.)
In main if I do signal(SIGINT, SIG_IGN); it ignores the signal correctly and doesn't exit but I now have no way of knowing if I recieved the SIGINT interrupt.
Earlier I was playing around with the sigaction struct but I could not find any real comprehensive documentation on it so I decided to go with just "raw" signal handling.
This was my sigaction code (same problem as above):
struct sigaction action;
action.sa_handler = sigHandle;
sigemptyset(&action.sa_mask);
action.sa_flags = 0;
sigaction(SIGINT, &action, 0);
Thanks for your help!
EDIT
OK SO After many many many hours of scowering through man pages and the internet I have happened across a (very) ghetto solution involving saving the stack pre-infinite loop then when the interrupt comes, doing what I need to do, then re-setting the stack back to where it was and calling the sigrelse() command to re-set any states that might have been changed and not re-loaded.
I understand that this is not the most elegant/efficient/or even socially acceptable solution to this problem but it works and as far as I can tell I am not leaking any memory anywhere so it's all good...
I am still looking for a solution to this problem and I view my stack re-setting shenanigins as only a temporary fix...
Thanks!
Also note you should not call stdio (or other non-reentrant functions) in signal handlers.
(your signal handler might be invoked in the middle of a malloc or it's C++ equivalent)
It is not. You just replacing SIGINT's handles with same function. How does you program perform wait?
If you have something like:
int main
{
// ...
int r = read(fd, &buff, read_size); // your program hangs here, waiting for the data.
// but if signal occurred during this period of time
// read will return immediately, and r may != read_size
return 0; // then it will go straight to return.
}