summaryrefslogtreecommitdiffstats
path: root/libsysutils/src/ServiceManager.cpp
blob: 700ac91b9c3cc7a138e245c58d27dee61687b2b6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <errno.h>

#include <sysutils/ServiceManager.h>

#define LOG_TAG "Service"
#include <cutils/log.h>
#include <cutils/properties.h>

ServiceManager::ServiceManager() {
}

int ServiceManager::start(const char *name) {
    if (isRunning(name)) {
        LOGW("Service '%s' is already running", name);
        return 0;
    }

    LOGD("Starting service '%s'", name);
    property_set("ctl.start", name);

    int count = 200;
    while(count--) {
        sched_yield();
        if (isRunning(name))
            break;
    }
    if (!count) {
        LOGW("Timed out waiting for service '%s' to start", name);
        errno = ETIMEDOUT;
        return -1;
    }
    LOGD("Sucessfully started '%s'", name);
    return 0;
}

int ServiceManager::stop(const char *name) {
    if (!isRunning(name)) {
        LOGW("Service '%s' is already stopped", name);
        return 0;
    }

    LOGD("Stopping service '%s'", name);
    property_set("ctl.stop", name);

    int count = 200;
    while(count--) {
        sched_yield();
        if (!isRunning(name))
            break;
    }

    if (!count) {
        LOGW("Timed out waiting for service '%s' to stop", name);
        errno = ETIMEDOUT;
        return -1;
    }
    LOGD("Sucessfully stopped '%s'", name);
    return 0;
}

bool ServiceManager::isRunning(const char *name) {
    char propVal[PROPERTY_VALUE_MAX];
    char propName[255];

    snprintf(propName, sizeof(propVal), "init.svc.%s", name);


    if (property_get(propName, propVal, NULL)) {
        if (!strcmp(propVal, "running"))
            return true;
    }
    return false;
}