ServiceManager.cpp revision b93e5812faffd3b6c5fb349072413aace31918d8
1#include <errno.h>
2#include <string.h>
3
4#include <sysutils/ServiceManager.h>
5
6#define LOG_TAG "Service"
7#include <cutils/log.h>
8#include <cutils/properties.h>
9
10ServiceManager::ServiceManager() {
11}
12
13int ServiceManager::start(const char *name) {
14    if (isRunning(name)) {
15        SLOGW("Service '%s' is already running", name);
16        return 0;
17    }
18
19    SLOGD("Starting service '%s'", name);
20    property_set("ctl.start", name);
21
22    int count = 200;
23    while(count--) {
24        sched_yield();
25        if (isRunning(name))
26            break;
27    }
28    if (!count) {
29        SLOGW("Timed out waiting for service '%s' to start", name);
30        errno = ETIMEDOUT;
31        return -1;
32    }
33    SLOGD("Sucessfully started '%s'", name);
34    return 0;
35}
36
37int ServiceManager::stop(const char *name) {
38    if (!isRunning(name)) {
39        SLOGW("Service '%s' is already stopped", name);
40        return 0;
41    }
42
43    SLOGD("Stopping service '%s'", name);
44    property_set("ctl.stop", name);
45
46    int count = 200;
47    while(count--) {
48        sched_yield();
49        if (!isRunning(name))
50            break;
51    }
52
53    if (!count) {
54        SLOGW("Timed out waiting for service '%s' to stop", name);
55        errno = ETIMEDOUT;
56        return -1;
57    }
58    SLOGD("Sucessfully stopped '%s'", name);
59    return 0;
60}
61
62bool ServiceManager::isRunning(const char *name) {
63    char propVal[PROPERTY_VALUE_MAX];
64    char propName[255];
65
66    snprintf(propName, sizeof(propVal), "init.svc.%s", name);
67
68
69    if (property_get(propName, propVal, NULL)) {
70        if (!strcmp(propVal, "running"))
71            return true;
72    }
73    return false;
74}
75