我目前使用adb shell在我的手机上启动可执行文件(二进制文件需要“ shell”用户权限)。 我想让进程尽可能长时间地在后台运行,但是每次断开USB线时,进程都会消失。
测试设备的操作系统是LineageOS / Android 8.1的非官方版本。
我尝试过:
我当前的代码如下,在带有CMake配置“ add_executable(libDaemonize.so Daemonize.c)”的标准NDK项目中编译,并在adb shell中使用 “ nohup /data/app/org.app.name/lib/arm/libDaemonize.so> / dev / null 2> / dev / null
/*Based on https://stackoverflow.com/a/17955149/11250128*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <syslog.h>
void INThandler(int);
static void skeleton_daemon()
{
pid_t pid;
/* Fork off the parent process */
pid = fork();
/* An error occurred */
if (pid < 0)
exit(EXIT_FAILURE);
/* Success: Let the parent terminate */
if (pid > 0) {
syslog (LOG_NOTICE, "From starter: PID: %d, PPID: %d\n", getpid(), getppid());
exit(EXIT_SUCCESS);
}
/* On success: The child process becomes session leader */
if (setsid() < 0)
exit(EXIT_FAILURE);
/* Catch, ignore and handle ALL signals */
int i;
for(i=1; i<32; i++) {
signal(i, INThandler);
}
/* Fork off for the second time*/
pid = fork();
/* An error occurred */
if (pid < 0)
exit(EXIT_FAILURE);
/* Success: Let the parent terminate */
if (pid > 0)
exit(EXIT_SUCCESS);
/* Set new file permissions */
umask(0);
/* Change the working directory to the root directory */
/* or another appropriated directory */
chdir("/");
/* Close all open file descriptors */
int x;
for (x = sysconf(_SC_OPEN_MAX); x>=0; x--)
{
close (x);
}
/* Open the log file */
openlog ("testdaemon", LOG_PID, LOG_DAEMON);
}
int main()
{
skeleton_daemon();
while (1)
{
syslog (LOG_NOTICE, "Daemon running. PID: %d, PPID: %d\n", getpid(), getppid());
sleep (1);
}
syslog (LOG_NOTICE, "Daemon terminated.");
closelog();
return EXIT_SUCCESS;
}
/*Define signal handlers to find out what signal kills us */
void INThandler(int sig)
{
syslog(LOG_CRIT, "Daemon received Signal %d", sig);
}
所有调用均成功完成并按预期进行(例如,以init / pid 1为父级的守护程序),但是一旦USB线断开连接,应用程序就会停止打印到syslog。
我最好的猜测是,Android系统会主动终止该进程,但是既没有Adbd日志(通过“ setproppersist.adb.trace_mask”激活),也没有在我搜索Adb源代码后找到任何证据。
>我觉得我想念一些明显的东西。 感谢您的想法。