File indexing completed on 2024-04-28 15:20:31

0001 /*
0002     This file is part of libkdbus
0003 
0004     SPDX-FileCopyrightText: 2019 Harald Sitter <sitter@kde.org>
0005 
0006     SPDX-License-Identifier: LGPL-2.0-or-later
0007 */
0008 
0009 #include <QCoreApplication>
0010 #include <QDebug>
0011 #include <QThread>
0012 #include <kdbusservice.h>
0013 
0014 // sigaction
0015 #include <signal.h>
0016 // close
0017 #include <unistd.h>
0018 
0019 // rlimit
0020 #include <sys/resource.h>
0021 #include <sys/time.h>
0022 
0023 // USR1.
0024 // Close all sockets and eventually ABRT. This mimics behavior during KCrash
0025 // handling. Closing all sockets will effectively disconnect us from the bus
0026 // and result in the daemon reclaiming all our service names and allowing
0027 // other processes to register them instead.
0028 void usr1_handler(int signum)
0029 {
0030     qDebug() << "usr1" << signum << SIGSEGV;
0031 
0032     // Close all remaining file descriptors so we drop off of the bus.
0033     struct rlimit rlp;
0034     getrlimit(RLIMIT_NOFILE, &rlp);
0035     for (int i = 3; i < (int)rlp.rlim_cur; i++) {
0036         close(i);
0037     }
0038 
0039     // Sleep a bit for good measure. We could actually loop ad infinitum here
0040     // as after USR1 we are expected to get killed. In the interest of sane
0041     // behavior we'll simply exit on our own as well though.
0042     sleep(4);
0043     abort();
0044 }
0045 
0046 // Simple application under test.
0047 // Closes all sockets on USR1 and aborts to simulate a kcrash shutdown behavior
0048 // which can result in a service registration race.
0049 int main(int argc, char *argv[])
0050 {
0051     qDebug() << "hello there!";
0052 
0053     struct sigaction action;
0054 
0055     action.sa_handler = usr1_handler;
0056     sigemptyset(&action.sa_mask);
0057     sigaddset(&action.sa_mask, SIGUSR1);
0058     action.sa_flags = SA_RESTART;
0059 
0060     if (sigaction(SIGUSR1, &action, nullptr) < 0) {
0061         qDebug() << "failed to register segv handler";
0062         return 1;
0063     }
0064 
0065     QCoreApplication app(argc, argv);
0066     QCoreApplication::setApplicationName("kdbussimpleservice");
0067     QCoreApplication::setOrganizationDomain("kde.org");
0068 
0069     KDBusService service(KDBusService::Unique);
0070     if (!service.isRegistered()) {
0071         qDebug() << "service not registered => exiting";
0072         return 1;
0073     }
0074     qDebug() << "service registered";
0075 
0076     int ret = app.exec();
0077     qDebug() << "exiting deadservice";
0078     return ret;
0079 }