Skip to content

Commit

Permalink
Forward all possible signals to child process
Browse files Browse the repository at this point in the history
Fixes #418.
  • Loading branch information
TheAssassin committed May 10, 2021
1 parent b4010f8 commit 3f901f6
Showing 1 changed file with 25 additions and 1 deletion.
26 changes: 25 additions & 1 deletion src/binfmt-bypass/main.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,23 @@ char* find_preload_library(bool is_32bit) {
return result;
}

// need to keep track of the subprocess pid in a global variable, as signal handlers in C(++) are simple interrupt
// handlers that are not aware of any state in main()
// note that we only connect the signal handler once we have created a subprocess, i.e., we don't need to worry about
// subprocess_pid not being set yet
// it's best practice to implement a check anyway, though
static pid_t subprocess_pid = 0;

void forwardSignal(int signal) {
if (subprocess_pid != 0) {
log_debug("forwarding signal %d to subprocess %ld\n", signal, subprocess_pid);
kill(subprocess_pid, signal);
} else {
log_error("signal %d received but no subprocess created yet, shutting down\n", signal);
exit(signal);
}
}

int main(int argc, char** argv) {
if (argc <= 1) {
log_message("Usage: %s <AppImage file> [...]\n", argv[0]);
Expand Down Expand Up @@ -182,7 +199,7 @@ int main(int argc, char** argv) {
}

// to keep alive the memfd, we launch the AppImage as a subprocess
if (fork() == 0) {
if ((subprocess_pid = fork()) == 0) {
// create new argv array, using passed filename as argv[0]
std::vector<char*> new_argv;

Expand Down Expand Up @@ -221,6 +238,13 @@ int main(int argc, char** argv) {
return EXIT_CODE_FAILURE;
}

// now that we have a subprocess and know its process ID, it's time to set up signal forwarding
// note that from this point on, we don't handle signals ourselves any more, but rely on the subprocess to exit
// properly
for (int i = 0; i < 32; ++i) {
signal(i, forwardSignal);
}

// wait for child process to exit, and exit with its return code
int status;
wait(&status);
Expand Down

0 comments on commit 3f901f6

Please sign in to comment.