libudev how to use poll with the file descriptor - c++

So, I have an application that I want to be notified of hotplug events on linux. Naturally, I looked at libudev and its API. I also found a useful tutorial on how to use select() with libudev. Following the tutorial and glancing at the API, I came up with this example program that waits for hotplug events and then outputs some basic information about the device that was just added or removed.
#include <poll.h>
#include <libudev.h>
#include <stdexcept>
#include <iostream>
udev* hotplug;
udev_monitor* hotplug_monitor;
void init()
{
// create the udev object
hotplug = udev_new();
if(!this->hotplug)
{
throw std::runtime_error("cannot create udev object");
}
// create the udev monitor
hotplug_monitor = udev_monitor_new_from_netlink(hotplug, "udev");
// start receiving hotplug events
udev_monitor_enable_receiving(hotplug_monitor);
}
void deinit()
{
// destroy the udev monitor
udev_monitor_unref(hotplug_monitor);
// destroy the udev object
udev_unref(hotplug);
}
void run()
{
// create the poll item
pollfd items[1];
items[0].fd = udev_monitor_get_fd(hotplug_monitor);
items[0].events = POLLIN;
items[0].revents = 0;
// while there are hotplug events to process
while(poll(items, 1, 50) > 0)
{
// XXX
std::cout << "hotplug[ " << items[0].revents << " ]" << std::endl;
// receive the relevant device
udev_device* dev = udev_monitor_receive_device(hotplug_monitor);
if(!dev)
{
// error receiving device, skip it
continue;
}
// XXX
std::cout << "hotplug[" << udev_device_get_action(dev) << "] ";
std::cout << udev_device_get_devnode(dev) << ",";
std::cout << udev_device_get_subsystem(dev) << ",";
std::cout << udev_device_get_devtype(dev) << std::endl;
// destroy the relevant device
udev_device_unref(dev);
// XXX
std::cout << "done" << std::endl;
// clear the revents
items[0].revents = 0;
}
}
int main(int args, char* argv[])
{
init();
while(true)
{
run();
}
deinit();
}
Well, it doesn't work. Here's the output I get when I plug in a usb mouse.
hotplug[ 1 ]
hotplug[add] /dev/bus/usb/008/002,usb,usb_device
done
hotplug[ 1 ]
hotplug[add]
At that point the program freezes and I have to stop it with Ctrl-C. What am I doing wrong?

The program doesn't actually stop; it continues running, but std::cout gets messed up when you try to print a NULL string (not all events have all properties). A fix is to make the three prints (devnode, subsystem, devtype) conditional.

Related

Possible to allow key bindings with MPV C API when no video (GUI) is being shown?

I am creating a background music player and I wanted to use the MPV C Plugin to do so, but my problem arrives when I disable displaying the video (with check_error(mpv_set_option_string(ctx, "vid", "no"));, this does the job of disabling the video, but then I can't use keys (like q (quit) or > (skip)) anymore... How do I allow them to be used in the terminal without the video GUI?
My Code:
#include <iostream>
#include <mpv/client.h>
static inline void check_error(int status)
{
if (status < 0)
{
std::cout << "mpv API error: " << mpv_error_string(status) << std::endl;
exit(1);
}
}
int main(int argc, char *argv[])
{
if (argc != 2)
{
std::cout << "pass a single media file as argument" << std::endl;
return 1;
}
mpv_handle *ctx = mpv_create();
if (!ctx)
{
std::cout << "failed creating context" << std::endl;
return 1;
}
check_error(mpv_set_option_string(ctx, "input-default-bindings", "yes"));
mpv_set_option_string(ctx, "input-vo-keyboard", "yes");
int val = 1;
check_error(mpv_set_option(ctx, "osc", MPV_FORMAT_FLAG, &val));
check_error(mpv_initialize(ctx));
const char *cmd[] = {"loadfile", argv[1], NULL};
check_error(mpv_command(ctx, cmd));
// THIS IS WHAT I USE TO DISABLE THE VIDEO
// check_error(mpv_set_option_string(ctx, "vid", "no"));
// Let it play, and wait until the user quits.
while (1)
{
mpv_event *event = mpv_wait_event(ctx, 10000);
std::cout << "event: " << mpv_event_name(event->event_id) << std::endl;
if (event->event_id == MPV_EVENT_SHUTDOWN)
break;
}
mpv_terminate_destroy(ctx);
return 0;
}
As you can see with mpv_set_option_string(ctx, "input-default-bindings", "yes") I allow it to use keybinding, but how do I make the keybinding works with just the terminal, since it only works when the GUI is visible? If you ran: mpv path/to/video.mp3 --no-video then the key bindings would still work fine, even without the video GUI.

Assertion when trying to a use a Boost.Interprocess message queue across a bunch of processes

I have the following reduced program that spins up a bunch of child processes and then uses a boost::interprocess::message_queue to send a message to each one. This works when number of processes is small (about 4 on my machine) but as that number rises I get the following message:
head (81473): "./a.out"
Assertion failed: (res == 0), function do_wait, file /usr/local/include/boost/interprocess/sync/posix/condition.hpp, line 175.
I'm guessing it's a problem with my synchronisation.. have I done something wrong or is the boost::interprocess::scoped_lock not enough?
My program is here:
#include <boost/interprocess/ipc/message_queue.hpp>
#include <boost/interprocess/sync/interprocess_mutex.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
#include <boost/process.hpp>
#include <iostream>
auto main(int argc, char **argv) -> int
{
namespace ip = boost::interprocess;
boost::filesystem::path self{argv[0]};
if (argc == 1) {
std::cout << "head (" << ::getpid() << "): " << self << std::endl;
// create a message queue.
ip::message_queue::remove("work_queue");
ip::message_queue tasks{ip::create_only, "work_queue", 100, sizeof(int)};
// mutex for writing to the queue.
ip::interprocess_mutex mutex{};
// spawn off a bunch of processes.
const auto cores{5 * std::thread::hardware_concurrency()};
std::vector<boost::process::child> workers{};
for (auto i = 0; i < cores; ++i) {
workers.emplace_back(self, "child");
}
// send message to each core.
for (auto i = 0; i < cores; ++i) {
ip::scoped_lock<decltype(mutex)> lock{mutex};
tasks.send(&i, sizeof(i), 0);
}
// wait for each process to finish.
for (auto &worker : workers) {
worker.wait();
}
} else if (argc == 2 && std::strcmp(argv[1], "child") == 0) {
// connect to message queue.
ip::message_queue tasks{ip::open_only, "work_queue"};
// mutex for reading from the queue.
ip::interprocess_mutex mutex{};
unsigned int priority;
ip::message_queue::size_type recvd_size;
{
ip::scoped_lock<decltype(mutex)> lock{mutex};
int number;
tasks.receive(&number, sizeof(number), recvd_size, priority);
std::cout << "child (" << ::getpid() << "): " << self << ", received: " << number << std::endl;
}
}
return 0;
}
You create an interprocess_mutex instance on the stack. So each process has it's own mutex and locking it does not synchronize anything. You need to create a shared memory region, place mutex there and then open the same shared memory region in child process to access the mutex created by parent process.

MHD_resume_connection() of libmicrohttpd not working properly with external select

I encountered some problems with MHD_suspend_connection() and MHD_resume_connection() in libmicrohttpd while using the external event loop. Afterwards I have wrote a small example (without error handling) below. My question is: What am I doing wrong? Or is it a bug in the library? It should work as far as I understand the manual. Using external select with suspend/resume is allowed explicitly.
The problem is that connections are not resumed correctly. Processing the connection does not continue right after calling MHD_resume_connection(). In some versions of my program, it did continue after another request was incomming. In other versions later requests was not handled at all (access_handler() was never called). In some of this versions I got a response for the first request while stopping libmicrohttpd. When I enable MHD_USE_SELECT_INTERNALLY and remove my external loop (let it sleep), everything works.
I tested it on Debian (libmicrohttpd 0.9.37) and Arch (libmicrohttpd 0.9.50). The problem exists on both systems but maybe the behavior was a little bit different.
#include <algorithm>
#include <csignal>
#include <cstring>
#include <iostream>
#include <vector>
#include <sys/select.h>
#include <microhttpd.h>
using std::cerr;
using std::cout;
using std::endl;
static volatile bool run_loop = true;
static MHD_Daemon *ctx = nullptr;
static MHD_Response *response = nullptr;
static std::vector<MHD_Connection*> susspended;
void sighandler(int)
{
run_loop = false;
}
int handle_access(void *cls, struct MHD_Connection *connection,
const char *url, const char *method, const char *version,
const char *upload_data, size_t *upload_data_size,
void **con_cls)
{
static int second_call_marker;
static int third_call_marker;
if (*con_cls == nullptr) {
cout << "New connection" << endl;
*con_cls = &second_call_marker;
return MHD_YES;
} else if (*con_cls == &second_call_marker) {
cout << "Suspending connection" << endl;
MHD_suspend_connection(connection);
susspended.push_back(connection);
*con_cls = &third_call_marker;
return MHD_YES;
} else {
cout << "Send response" << endl;
return MHD_queue_response(connection, 200, response);
}
}
void myapp()
{
std::signal(SIGINT, &sighandler);
std::signal(SIGINT, &sighandler);
ctx = MHD_start_daemon(MHD_USE_DUAL_STACK //| MHD_USE_EPOLL
| MHD_USE_SUSPEND_RESUME | MHD_USE_DEBUG,
8080, nullptr, nullptr,
&handle_access, nullptr,
MHD_OPTION_END);
response = MHD_create_response_from_buffer(4, const_cast<char*>("TEST"),
MHD_RESPMEM_PERSISTENT);
while (run_loop) {
int max;
fd_set rs, ws, es;
struct timeval tv;
struct timeval *tvp;
max = 0;
FD_ZERO(&rs);
FD_ZERO(&ws);
FD_ZERO(&es);
cout << "Wait for IO activity" << endl;
MHD_UNSIGNED_LONG_LONG mhd_timeout;
MHD_get_fdset(ctx, &rs, &ws, &es, &max);
if (MHD_get_timeout(ctx, &mhd_timeout) == MHD_YES) {
//tv.tv_sec = std::min(mhd_timeout / 1000, 1ull);
tv.tv_sec = mhd_timeout / 1000;
tv.tv_usec = (mhd_timeout % 1000) * 1000;
tvp = &tv;
} else {
//tv.tv_sec = 2;
//tv.tv_usec = 0;
//tvp = &tv;
tvp = nullptr;
}
if (select(max + 1, &rs, &ws, &es, tvp) < 0 && errno != EINTR)
throw "select() failed";
cout << "Handle IO activity" << endl;
if (MHD_run_from_select(ctx, &rs, &ws, &es) != MHD_YES)
throw "MHD_run_from_select() failed";
for (MHD_Connection *connection : susspended) {
cout << "Resume connection" << endl;
MHD_resume_connection(connection);
}
susspended.clear();
}
cout << "Stop server" << endl;
MHD_stop_daemon(ctx);
}
int main(int argc, char *argv[])
{
try {
myapp();
} catch (const char *str) {
cerr << "Error: " << str << endl;
cerr << "Errno: " << errno << " (" << strerror(errno) << ")" << endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
I've compiled and run your sample on Windows and am seeing the same behavior w/ 0.9.51.
It's not a bug in microhttpd. The problem is that you are resuming a connection before queuing a response on it. The only code you have that creates a response relies on more activity on the connection so it's a catch-22.
The point of MHD_suspend_connection/MHD_resume_connection is to not block new connections while long-running work is going on. Thus typically after suspending the connection you need to kick off that work on another thread to continue while the listening socket is maintained. When that thread has queued the response it can resume the connection and the event loop will know it is ready to send back to the client.
I'm not sure of your other design requirements but you may not need to be implementing external select. That is to say, suspend/resume does not require it (I've used suspend/resume just fine with MHD_USE_SELECT_INTERNALLY, e.g.).
I dont know if it's mentioned. But you have a multi-threading bug, and perhaps, "intent bug". As the lib, may or may not use threads, depending on other factors. You can see if you are using threads, by printing the thread id, from the functions. But, your answerToConnection function, sets your vector (without mutex protection), and then you are immediately looking at it, and retrying potentially from another thread. this goes against the intent/purpose of suspend/retry, since suspend is really for something taking "a long time". The gotcha, is that you dont own the calling code, so, you dont know when it's totally done. however, you can age your retry, with a timeval, so, you dont retry too soon. at least a value of tv_usec +1. you need to note, that you are using the vector from two or more threads, without mutex protection.

How to find out whether child process still is running?

I am spawning a process in my application:
int status = posix_spawnp(&m_iProcessHandle, (char*)strProgramFilepath.c_str(), NULL, NULL, argsWrapper.m_pBuffer, NULL);
When I want to see if the process is still running, I use kill:
int iReturn = kill(m_iProcessHandle,0);
But after the spawned process has finished its work, it hangs around. The return value on the kill command is always 0. Not -1. I am calling kill from within the code, but if I call it from the command line, there is no error - the spawned process still exists.
Only when my application exits does the command-line kill return "No such process".
I can change this behavior in my code with this:
int iResult = waitpid(m_iProcessHandle, &iStatus, 0);
The call to waitpd closes down the spawned process and I can call kill and get -1 back, but by then I know the spawned process is dead.
And waitpd blocks my application!
How can I test a spawned processes to see if it is running, but without blocking my application?
UPDATE
Thanks for the help! I have implemented your advise and here is the result:
// background-task.cpp
//
#include <spawn.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <signal.h>
#include "background-task.h"
CBackgroundTask::CBackgroundTask()
{
// Initialize member variables
m_iProcessHandle = 0;
}
CBackgroundTask::~CBackgroundTask()
{
// Clean up (kill first)
_lowLevel_cleanup(true);
}
bool CBackgroundTask::IsRunning()
{
// Shortcuts
if (m_iProcessHandle == 0)
return false;
// Wait for the process to finish
int iStatus = 0;
int iResult = waitpid(m_iProcessHandle, &iStatus, WNOHANG);
return (iResult != -1);
}
void CBackgroundTask::Wait()
{
// Wait (clean up without killing)
_lowLevel_cleanup(false);
}
void CBackgroundTask::Stop()
{
// Stop (kill and clean up)
_lowLevel_cleanup(true);
}
void CBackgroundTask::_start(const string& strProgramFilepath, const string& strArgs, int iNice /*=0*/)
{
// Call pre-start
_preStart();
// Split the args and build array of char-strings
CCharStringAarray argsWrapper(strArgs,' ');
// Run the command
int status = posix_spawnp(&m_iProcessHandle, (char*)strProgramFilepath.c_str(), NULL, NULL, argsWrapper.m_pBuffer, NULL);
if (status == 0)
{
// Process created
cout << "posix_spawn process=" << m_iProcessHandle << " status=" << status << endl;
}
else
{
// Failed
cout << "posix_spawn: error=" << status << endl;
}
// If process created...
if(m_iProcessHandle != 0)
{
// If need to adjust nice...
if (iNice != 0)
{
// Change the nice
stringstream ss;
ss << "sudo renice -n " << iNice << " -p " << m_iProcessHandle;
_runCommand(ss.str());
}
}
else
{
// Call post-stop success=false
_postStop(false);
}
}
void CBackgroundTask::_runCommand(const string& strCommand)
{
// Diagnostics
cout << "Running command: " << COUT_GREEN << strCommand << endl << COUT_RESET;
// Run command
system(strCommand.c_str());
}
void CBackgroundTask::_lowLevel_cleanup(bool bKill)
{
// Shortcuts
if (m_iProcessHandle == 0)
return;
// Diagnostics
cout << "Cleaning up process " << m_iProcessHandle << endl;
// If killing...
if (bKill)
{
// Kill the process
kill(m_iProcessHandle, SIGKILL);
}
// Diagnostics
cout << "Waiting for process " << m_iProcessHandle << " to finish" << endl;
// Wait for the process to finish
int iStatus = 0;
int iResult = waitpid(m_iProcessHandle, &iStatus, 0);
// Diagnostics
cout << "waitpid: status=" << iStatus << " result=" << iResult << endl;
// Reset the process-handle
m_iProcessHandle = 0;
// Call post-stop with success
_postStop(true);
// Diagnostics
cout << "Process cleaned" << endl;
}
Until the parent process calls one of the wait() functions to get the exit status of a child, the child stays around as a zombie process. If you run ps during this time, you'll see that the process is still there in the Z state. So kill() returns 0 because the process exists.
If you don't need to get the child's status, see How can I prevent zombie child processes? for how you can make the child disappear immediately when it exits.

"Safely" terminate a running C++ program on keypress?

I'm trying to write a simulation that will carry on running until I press a certain key (like 'q' for quit). Then after I press that, I want the program to finish writing the data its currently writing, close files, then gracefully exit (as opposed to just pressing ctrl+c to force the program to stop). Is there any way to do this on C++?
Thanks
Have the user press CTRL-C, but install a signal handler to deal with it. In the signal handler, set a global boolean variable, for example user_wants_to_quit. Then your sim loop can look like:
while ( work_to_be_done && !user_wants_to_quit) {
…
}
// Loop exited, clean up my data
A complete POSIX program (sorry, if you were hoping for Microsoft Windows), including setting and restoring the SIGINT (CTRL-C) handler:
#include <iostream>
#include <signal.h>
namespace {
sig_atomic_t user_wants_to_quit = 0;
void signal_handler(int) {
user_wants_to_quit = 1;
}
}
int main () {
// Install signal handler
struct sigaction act;
struct sigaction oldact;
act.sa_handler = signal_handler;
sigemptyset(&act.sa_mask);
act.sa_flags = 0;
sigaction(SIGINT, &act, &oldact);
// Run the sim loop
int sim_loop_counter = 3;
while( (sim_loop_counter--) && !user_wants_to_quit) {
std::cout << "Running sim step " << sim_loop_counter << std::endl;
// Sim logic goes here. I'll substitute a sleep() for the actual
// sim logic
sleep(1);
std::cout << "Step #" << sim_loop_counter << " is now complete." << std::endl;
}
// Restore old signal handler [optional]
sigaction(SIGINT, &oldact, 0);
if( user_wants_to_quit ) {
std::cout << "SIM aborted\n";
} else {
std::cout << "SIM complete\n";
}
}