Reputation: 403
I have a program which should run in the background. I'm trying to trigger it using adb and get the following behavior:
adb shell "app &"
adb shell ps | grep myapp
shows that the app is not running.
adb shell
$app &
$exit
Result with terminal not responding. After killing adb process, the terminal is freed then when I check by:
adb shell ps | grep myapp
I see the app is running in the background.
Can someone explain this behavior? How can I run the app from command line and have it run in the background via cli?
Android Debug Bridge version 1.0.32
Revision 9e28ac08b3ed-android
Upvotes: 1
Views: 1446
Reputation: 1522
You app is a child of the shell that is spawned when you connect with ADB. When you exit the shell, your app is killed because the shell is killed. You should detach your app from the shell:
Using nohup:
adb shell "nohup app &"
Using daemonize (available on some Android systems):
adb shell daemonize app
adb shell toybox daemonize app
And if you have troubles (like me) with nohup that hangs the adb shell command, and if daemonize is not available, you can program it yourself in C, as follows:
#include <stdio.h>
#include <signal.h>
#include <sys/types.h>
#include <unistd.h>
#include <unistd.h>
int main(int argc, char ** argv)
{
int pid = fork();
if (pid > 0) {
printf("Father dies\n");
return 0;
}
/* redirect_fds(): redirect stdin, stdout, and stderr to /dev/NULL */
(void) close(0);
(void) close(1);
(void) close(2);
(void) dup(0);
(void) dup(0);
while (1)
{
printf("Child runs silently\n");
sleep(1);
/* Do long stuff in backgroudn here */
}
return 0;
}
Upvotes: 2