java 端启动一个demoService,demoService启动时就会通过AIDL 启动另外一个进程的guardService
>
android:process="com.gdut.persistentservice.guradService"
>
</service>
public int onStartCommand(Intent intent, int flags, int startId) {
if(intent==null)return super.onStartCommand(intent, flags, startId);
String action = intent.getAction();
if(action==null)return super.onStartCommand(intent, flags, startId);
log.d("demoService: onStartCommand:"+action);
if(action.equals(START_NATIVATE)){
bindAidlService(this);
}
return super.onStartCommand(intent, flags, startId);
}
在guardService 里通过 JNI 去fork 一个子进程,并且在子进程里启动一个线程,去监控service
我这里为了方便debug观察,就只在fork 出来的父进程 和子进程,都启动一个线程,都去循环打log,观察他们的运行情况,能否在长按home键出来的多任务界面划掉后,能否继续运行
void *thread_run(void* arg){
int count =20;//*((int*)arg);
LOGD("native thread count:%d",count);
for(int i=0;i<count;i++){
LOGD("native thread run:%d",i);
sleep(1);
}
}
void *fork_thread_run(void* arg){
int count =20;//*((int*)arg);
LOGD("native thread count:%d",count);
for(int i=0;i<count;i++){
LOGD("native fork thread run:%d",i);
sleep(1);
}
}
void start_thread(){
pid_t fpid;
fpid = fork();
if(fpid<0){
LOGD("native fork error");
}else if(fpid == 0){
LOGD("native fork child");
pthread_t id;
int count=10;
pthread_create(&id,NULL,fork_thread_run,(void*)&count);
}else{
LOGD("native fork parent");
pthread_t id;
int count=10;
pthread_create(&id,NULL,thread_run,(void*)&count);
}
}
发现,当程序安装进去后第一次运行,划掉改任务后,子进程的log会继续打,其他进程全被停止了。但是第二次运行,发现子进程会fatal,看NDK 的log,
backtrace:
#00 pc 0003806c /system/lib/libc.so (nanosleep+8)
#01 pc 00021a8f /system/lib/libc.so (sleep+38)
#02 pc 00000d65 /data/app/com.gdut.persistentservice-1/lib/arm/libserviceguard.so (fork_thread_run(void*)+44) //00000d65运行的是sleep(1)
#03 pc 000137ab /system/lib/libc.so (__pthread_start(void*)+30)
#04 pc 0001188b /system/lib/libc.so (__start_thread+6)
发现死在 sleep 方法这里,换成 usleep 也是会死。这里我百思不得其解啊,求高人指点迷津,还是我这种fork 出一个进程再开线程的写法不对啊,求指引明路