Search code examples
c++multithreadingc++14fuse

Thread killed when application is backgrounded?


I'm developing a fuse filesystem and before calling fuse_main_real() I'm starting a std::thread in a class instance to do some background work.

this->t_receive = new std::thread([this] { this->receive(); });

However, it seems like fuse_main_real() kills this thread when going into background.
If I start the program with the -f option, which tells fuse to stay in the foreground, the problem does not occur and the thread survives.

I'm not sure what fuse does to go into background.

How do I make my thread survive being backgrounded?


Edit: Here's a basic example that exposes the problem:

#define FUSE_USE_VERSION 30

#include <iostream>
#include <thread>

#include <fuse.h>

static void thread_method()
{
        while (true)
        {
                std::cout << "test" << std::endl;
                std::this_thread::sleep_for(std::chrono::seconds(1));
        }
}

struct testop : fuse_operations
{ };

static struct testop ops;

int main(int argc, char** argv)
{
        std::thread(thread_method).detach();
        fuse_main_real(argc, argv, &ops, sizeof(fuse_operations), NULL);
}

Compile with

g++ -D_FILE_OFFSET_BITS=64 `pkg-config --cflags fuse` -lfuse -lpthread -std=c++14 -o test.o test.cpp

Command that works (repeatedly says "test"):

./test.o -f /home/test/testmountpoint

Command that doesn't work and shows the problem (says "test" once):

./test.o /home/test/testmountpoint

Solution

  • The libfuse wiki says that

    Miscellaneous threads should be started from the init() method. Threads started before fuse_main() will exit when the process goes into the background.