I'm trying to build a GUI for a program I've been writing. I figured I'd use QT because it seems simple enough, it's free, I have an OK understanding of how the API works. Now, most of my business logic is actually written in C, mainly because it deals heavily with low-level C libraries, but it seems simple enough to call from C++. Right?
Well, no, as it turns out.
Code:
int main(int argc, const char *argv[]) {
handle_arguments(argc, argv);
initialize_fork(argv[0]);
sleep(1); // Or do_whatever(); doesn't matter
terminate_fork();
}
This is a paraphrase of the minimal code I've been banging my head against for a while now. What initialize_fork() does is creates a Unix socket-pair, dupes them to predefined FD numbers + closes the originals, then forks + execs. Communication between the main process and a fork happens across these file descriptors. terminate_fork() simply sends a message instructing the fork to
disconnect itself (and its own children, if it has any). If I compile this "normally" with GCC or G++, everything works as expected. But as soon as I link QT6,
without even writing QT code, I get an error at terminate_fork()'s calling of sendmsg() to the child process; perror prints "Bad file descriptor." Strangely, I can communicate over the file descriptor fine if the communication happens
before the program is about to end (say where sleep(1) is); it's just trying to communicate when the program is about to exit that runs into this problem.My only guess is that QT is somehow closing the socket or marking it as unusable as soon as it detects it's about to end and causing a race condition between its cleanup code and sendmsg(), which baffles my mind -- where is it getting a list of open file descriptors it had no part in creating, and why is it then deciding to close them? Would anyone know if there's a way to make QT keep its hands off random file descriptors it has no business knowing about? Or am I being
exceptional and something else is going on? Either way, I'd really rather avoid rewriting the C code/anything not in my main function as much as possible, which is why I'm not using QT's dedicated socket type and handlers in the first place. I'd appreciate any insight.
I suspect what I'll have to do is send a SIGTERM to the child and use a signal handler to clean up, but I'd at least like to figure out why the code I have isn't working, and if there's any way to wrangle QT into compliance.