How to run a script in background from adb shell?


Question

I have a problem with USB tethering on my rooted Nougat phone (LineageOS). After some time phone stops USB tethering. To fix that I run the following script like this:



adb shell
su
nohup sh tether.sh &
exit
exit


tether.sh



#!/system/bin/sh
service list
while true;
do
if ! pidof -s dnsmasq > /dev/null
then
echo -n "Connectivity lost at "
date -u +%FT%TZ
echo "Waiting 3 seconds..."
sleep 3
echo "Calling ConnectivityManager.setUsbTethering(false)"
service call connectivity 33 i32 0 2>&1
sleep 3
echo "Calling ConnectivityManager.setUsbTethering(true)"
service call connectivity 33 i32 1 2>&1
echo "Waiting 3 seconds..."
fi
sleep 3
done


Problem: If I use nohup my call to service call connectivity fails with service not found. And I put service list on top of the script which returns Found 0 services:. However the same commands work when ran directly from adb shell; su.



Why service call doesn't work inside this background script? Does it need the same tty to work?


Answer

Processes receive signals from other processes or kernel as a warning or as a request to make some change in state. Receiving processes can block, ignore or catch signals, except SIGKILL which does what the name says. A process receives SIGHUP (hangup signal) when its controlling terminal (virtual or pseudo) disconnects or its controlling process (which is usually a shell) terminates. Quoted from adb shell source:




PTYs automatically send SIGHUP to the slave-side process when the master side of the PTY closes




* See Terminals and Shells on Android for details on PTYs



Process can then handle the signal to continue its execution or just gets killed by the kernel.



nohup makes a process run (usually in background) by simply ignoring SIGHUP even if the controlling terminal closes. Additionally if FDs 0, 1 and 2 of the process are attached to the terminal, nohup redirects STDIN from /dev/null and STDOUT/STDERR to nohup.out file.



Android's built-in /system/bin/nohup has some bad implementation like many other applets of toybox. It replaces STDIN with nothing and leaves STDERR attached to the terminal. So all shell commandline tools which are related to system_server behave unexpectedly because of no FD 0.



Solution is to use nohup e.g. from busybox or do:



nohup tether.sh </dev/null &


Or without nohup:



tether.sh </dev/null &>/sdcard/usb.log &


In order to make sure a program ignores SIGHUP, add trap '' 1 to script above the program to be executed. But it's not required with Android's default MirBSD Korn Shell (/system/bin/sh) which doesn't send SIGHUP to all jobs (children processes) in the same session i.e. attached to the same terminal. So nohup or trap isn't essentially required, whether shell exits or gets killed.



Secondly mksh doesn't detach from terminal(s) completely because in addition to STDIN/OUT/ERR, it attaches to /dev/tty directly (ref). So detaching FDs 0/1/2 doesn't suffice. However there's a daemon mode which completely detaches the command from terminal:



/system/bin/sh -T- tether.sh


Also mksh unblocks all signals, though not relevant here.



bash provides better job management; user can configure with huponexit whether or not to always send SIGHUP to all jobs on exit (ref). Bash's built-in disown command can be used to exclude jobs from receiving signals.



To keep script running in foreground, a multiplexer like tmux or screen can be used. That's what I do, particularly with su binaries from rooting solutions which don't detach (due to limited implementation of pseudo-terminals), when a program is running in background. See this issue for details.



RELATED: How to run an executable on boot and keep it running?


Topics


2D Engines   3D Engines   9-Patch   Action Bars   Activities   ADB   Advertisements   Analytics   Animations   ANR   AOP   API   APK   APT   Architecture   Audio   Autocomplete   Background Processing   Backward Compatibility   Badges   Bar Codes   Benchmarking   Bitmaps   Bluetooth   Blur Effects   Bread Crumbs   BRMS   Browser Extensions   Build Systems   Bundles   Buttons   Caching   Camera   Canvas   Cards   Carousels   Changelog   Checkboxes   Cloud Storages   Color Analysis   Color Pickers   Colors   Comet/Push   Compass Sensors   Conferences   Content Providers   Continuous Integration   Crash Reports   Credit Cards   Credits   CSV   Curl/Flip   Data Binding   Data Generators   Data Structures   Database   Database Browsers   Date &   Debugging   Decompilers   Deep Links   Dependency Injections   Design   Design Patterns   Dex   Dialogs   Distributed Computing   Distribution Platforms   Download Managers   Drawables   Emoji   Emulators   EPUB   Equalizers &   Event Buses   Exception Handling   Face Recognition   Feedback &   File System   File/Directory   Fingerprint   Floating Action   Fonts   Forms   Fragments   FRP   FSM   Functional Programming   Gamepads   Games   Geocaching   Gestures   GIF   Glow Pad   Gradle Plugins   Graphics   Grid Views   Highlighting   HTML   HTTP Mocking   Icons   IDE   IDE Plugins   Image Croppers   Image Loaders   Image Pickers   Image Processing   Image Views   Instrumentation   Intents   Job Schedulers   JSON   Keyboard   Kotlin   Layouts   Library Demos   List View   List Views   Localization   Location   Lock Patterns   Logcat   Logging   Mails   Maps   Markdown   Mathematics   Maven Plugins   MBaaS   Media   Menus   Messaging   MIME   Mobile Web   Native Image   Navigation   NDK   Networking   NFC   NoSQL   Number Pickers   OAuth   Object Mocking   OCR Engines   OpenGL   ORM   Other Pickers   Parallax List   Parcelables   Particle Systems   Password Inputs   PDF   Permissions   Physics Engines   Platforms   Plugin Frameworks   Preferences   Progress Indicators   ProGuard   Properties   Protocol Buffer   Pull To   Purchases   Push/Pull   QR Codes   Quick Return   Radio Buttons   Range Bars   Ratings   Recycler Views   Resources   REST   Ripple Effects   RSS   Screenshots   Scripting   Scroll Views   SDK   Search Inputs   Security   Sensors   Services   Showcase Views   Signatures   Sliding Panels   Snackbars   SOAP   Social Networks   Spannable   Spinners   Splash Screens   SSH   Static Analysis   Status Bars   Styling   SVG   System   Tags   Task Managers   TDD &   Template Engines   Testing   Testing Tools   Text Formatting   Text Views   Text Watchers   Text-to   Toasts   Toolkits For   Tools   Tooltips   Trainings   TV   Twitter   Updaters   USB   User Stories   Utils   Validation   Video   View Adapters   View Pagers   Views   Watch Face   Wearable Data   Wearables   Weather   Web Tools   Web Views   WebRTC   WebSockets   Wheel Widgets   Wi-Fi   Widgets   Windows   Wizards   XML   XMPP   YAML   ZIP Codes