Waybar/src/main.cpp

119 lines
2.8 KiB
C++
Raw Normal View History

2022-04-06 06:37:19 +00:00
#include <spdlog/spdlog.h>
#include <sys/types.h>
#include <sys/wait.h>
2018-08-08 21:54:58 +00:00
#include <csignal>
#include <list>
#include <mutex>
2022-04-06 06:37:19 +00:00
#include "client.hpp"
2018-08-08 21:54:58 +00:00
std::mutex reap_mtx;
std::list<pid_t> reap;
volatile bool reload;
void* signalThread(void* args) {
int err, signum;
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, SIGCHLD);
while (true) {
err = sigwait(&mask, &signum);
if (err != 0) {
spdlog::error("sigwait failed: {}", strerror(errno));
continue;
}
switch (signum) {
case SIGCHLD:
spdlog::debug("Received SIGCHLD in signalThread");
if (!reap.empty()) {
reap_mtx.lock();
for (auto it = reap.begin(); it != reap.end(); ++it) {
if (waitpid(*it, nullptr, WNOHANG) == *it) {
spdlog::debug("Reaped child with PID: {}", *it);
it = reap.erase(it);
}
}
reap_mtx.unlock();
}
break;
default:
2022-04-06 06:37:19 +00:00
spdlog::debug("Received signal with number {}, but not handling", signum);
break;
}
}
}
void startSignalThread(void) {
int err;
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, SIGCHLD);
// Block SIGCHLD so it can be handled by the signal thread
// Any threads created by this one (the main thread) should not
// modify their signal mask to unblock SIGCHLD
err = pthread_sigmask(SIG_BLOCK, &mask, nullptr);
if (err != 0) {
spdlog::error("pthread_sigmask failed in startSignalThread: {}", strerror(err));
exit(1);
}
pthread_t thread_id;
err = pthread_create(&thread_id, nullptr, signalThread, nullptr);
if (err != 0) {
spdlog::error("pthread_create failed in startSignalThread: {}", strerror(err));
exit(1);
}
}
int main(int argc, char* argv[]) {
2018-08-08 21:54:58 +00:00
try {
auto client = waybar::Client::inst();
std::signal(SIGUSR1, [](int /*signal*/) {
for (auto& bar : waybar::Client::inst()->bars) {
bar->toggle();
2018-08-08 21:54:58 +00:00
}
});
std::signal(SIGUSR2, [](int /*signal*/) {
2022-04-06 06:37:19 +00:00
spdlog::info("Reloading...");
reload = true;
waybar::Client::inst()->reset();
});
std::signal(SIGINT, [](int /*signal*/) {
spdlog::info("Quitting.");
reload = false;
waybar::Client::inst()->reset();
});
2019-03-18 17:46:44 +00:00
for (int sig = SIGRTMIN + 1; sig <= SIGRTMAX; ++sig) {
std::signal(sig, [](int sig) {
for (auto& bar : waybar::Client::inst()->bars) {
2019-03-18 17:46:44 +00:00
bar->handleSignal(sig);
}
});
}
startSignalThread();
2019-03-18 17:46:44 +00:00
auto ret = 0;
do {
reload = false;
ret = client->main(argc, argv);
} while (reload);
delete client;
return ret;
2018-08-08 21:54:58 +00:00
} catch (const std::exception& e) {
2019-05-18 23:44:45 +00:00
spdlog::error("{}", e.what());
2018-08-08 21:54:58 +00:00
return 1;
} catch (const Glib::Exception& e) {
2019-05-18 23:44:45 +00:00
spdlog::error("{}", static_cast<std::string>(e.what()));
2018-08-08 21:54:58 +00:00
return 1;
}
}