init.rc中声明某个服务:
service sample_service /system/bin/sample_service
disabled
oneshot
启动这个服务:
property_set("ctl.start","sample_service");
结束这个服务:
property_set("ctl.stop","sample_service");
看了源码,还可以重启它。
property_set("ctl.restart","sample_service");
相关源码:
property_service.c
void handle_property_set_fd() { if(memcmp(msg.name,"ctl.",4) == 0) { // Keep the old close-socket-early behavior when handling // ctl.* properties. close(s); if (check_control_perms(msg.value, cr.uid, cr.gid, source_ctx)) { handle_control_message((char*) msg.name + 4, (char*) msg.value); } else { ERROR("sys_prop: Unable to %s service ctl [%s] uid:%d gid:%d pid:%d\n", msg.name + 4, msg.value, cr.uid, cr.gid, cr.pid); } } }
void handle_control_message(const char *msg, const char *arg) { if (!strcmp(msg,"start")) { msg_start(arg); } else if (!strcmp(msg,"stop")) { msg_stop(arg); } else if (!strcmp(msg,"restart")) { //重启 msg_stop(arg); msg_start(arg); } else { ERROR("unknown control msg '%s'\n", msg); } }
static void msg_start(const char *name) { struct service *svc; char *tmp = NULL; char *args = NULL; if (!strchr(name, ':')) svc = service_find_by_name(name); else { tmp = strdup(name); args = strchr(tmp, ':'); *args = '\0'; args++; svc = service_find_by_name(tmp); } if (svc) { service_start(svc, args); } else { ERROR("no such service '%s'\n", name); } if (tmp) free(tmp); }
看来在“:”后面加参数就可以了。例如:
property_set("ctl.start","sample_service:arg0");
如果要加入多个参数,不知道是否和命令行中一样,用空格分隔即可。实测:
//sample_service.c int main(int argc,char *argv[]) { char *arg0, *arg1; if(argc < 3) { printf("param num: %d\n", argc); return 1; } arg0 = *++argv; arg1= *++argv; printf("arg0=%s, arg1=%s\n", arg0, arg1); }
property_set("ctl.start","sample_service:hello world");
输出结果:
hello, world
测试成功