android reboot 1

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <cutils/properties.h>
#include <cutils/android_reboot.h>
#include <unistd.h>

int main(int argc, char* argv[]) {
int ret;
size_t prop_len;
char property_val[PROPERTY_VALUE_MAX];
static const char reboot[] = "reboot";
const char* cmd = reboot;
char* optarg = "";

opterr = 0;
do {
    int c;
    //#include <unistd.h>
    //參數argc和argv:
    // 通常是從main的參數直接傳遞而來,argc是參數的數量,argv是一個常量字符串數組的地址
    c = getopt(argc, argv, "p");

    if (c == -1) {
        break;
    }

    switch (c) {
    //adb reboot p 出發關機
    case 'p':
        cmd = "shutdown";
        break;
    case '?':
        fprintf(stderr, "usage: %s [-p] [rebootcommand]\n", argv[0]);
        //exit(0): 正常執行程序並退出程序。
        //exit(1): 非正常執行導致退出程序。
        //#define EXIT_FAILURE 1
        //#define EXIT_SUCCESS 0
        exit(EXIT_FAILURE);
    }
} while (1);
//int optind:argv的當前索引值。當getopt函數在while循環中使用時,剩下的字符串爲操作數,下標從optind到argc-1
//異常處理
if(argc > optind + 1) {
    fprintf(stderr, "%s: too many arguments\n", argv[0]);
    exit(EXIT_FAILURE);
}
if (argc > optind)
    optarg = argv[optind];
if (!optarg || !optarg[0]) optarg = "shell";

prop_len = snprintf(property_val, sizeof(property_val), "%s,%s", cmd, optarg);
if (prop_len >= sizeof(property_val)) {
    fprintf(stderr, "%s command too long: %s\n", cmd, optarg);
    exit(EXIT_FAILURE);
}

//#define ANDROID_RB_PROPERTY "sys.powerctl"
//對變量sys.powerctl 進行賦值
//property_set 》<cutils/properties.h> 》properties.cpp
ret = property_set(ANDROID_RB_PROPERTY, property_val);
if (ret < 0) {
    perror(cmd);
    exit(EXIT_FAILURE);
}

    // Don't return early. Give the reboot command time to take effect
    // to avoid messing up scripts which do "adb shell reboot && adb wait-for-device"
    if (cmd == reboot) {
        while (1) {
        //#include <unistd.h>
            // 讓進程暫停
            pause();
        }
    }

    fprintf(stderr, "Done\n");
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章