I am working on an automatic shutdown based on an external signal (through a digital IO line), on a BB black, running Debian Jessie.
I build a program that monitors the digital line and when that line goes high, the program calls
system("/sbin/shutdown -h now");
When I run that program interactively, it takes anywhere between 6 to 10 seconds to shutdown following the digital line flip. I use an LED to tell me when the process detects the bit flip so I can reliably count the time to shutdown. The actual shutdown is evident because all the lights go off. At that point I have to recycle power to start again, which is exactly what I want.
However, when I put the same program to run as a service (by adding a service in /lib/systemd/ and using systemctl to start it), the system takes over 30 seconds to shutdown, sometimes a minute or two. I know the program is running as a service because I can see the LED I am using as feedback. The LED changes blink rate when the 'service' detects the GPIO change so I can tell the program is getting to the point of making the system call, it just takes so much longer. In fact, initially I thought it did not work, only to have the system shutdown on my suddenly a couple of minutes later.
So the situation is that a program running directly goes through a shutdown almost instantaneously but when run through a service, it takes significantly longer. Any idea why?
By the way, I have also tried
sync();
reboot(LINUX_REBOOT_CMD_POWER_OFF);
instad of system("/sbin/shutdown -h now'), and I get more or less the same behavior.