Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Run a command detached from its parent so the parent can die w/o killing its child

Since last week I fail to implement an update feature for my program. I've packaged all into *.ipk files so it can be installed/updated with the package manager opkg.

The package itself is systemd aware and will stop/disable start/enable restart the service as it deems necessary.

The script itself calls opkg install as the only important part. Everything else is for debugging purposes, which did not help at all.

if ( fork() == 0 ) {
    setsid();

    if ( fork() == 0 ) {
        setsid();
        setpgid(0, 0);
        daemon(0, 0);
        execl("/etc/ifmii/scripts/update.sh", (char*)0);
    } else {
        wait(nullptr);
        std::this_thread::sleep_for(std::chrono::milliseconds(20000));
        _exit(0);
    }
}

The code above is the result of my trials. The forks do fork, but it does not detach properly from its parent.

I can confirm, that the script and the install command is at least startet. But the Install fails.

I suspect the install fails because systemd stops the parent process calling the update command, and with it, all children die.

What else could i try? Is there something wrong with my approach? How does one normally do this?

How do I run a command/script from a program which exits before the script/command it called exits?

like image 729
bioaster Avatar asked Oct 23 '25 16:10

bioaster


1 Answers

Ok. I think i've found an answer.

I use the system() call together with systemd-run. With this any command can be run completly unaware of any parent-child relationship.

                system("systemd-run opkg install --force-reinstall --force-downgrade --force-overwrite $(find /media -type f ! -path '*\\.*/*' -iname '*.ipk')");

No forking required. All of tehe code above replaces my initial code.

like image 88
bioaster Avatar answered Oct 27 '25 05:10

bioaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!