`
月下独酌
  • 浏览: 130516 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

app native socket

 
阅读更多
编写一个简单系统服务,功能很简单,接受命令,返回字符串。
需要在init.rc中定义服务的镜像名称和socket资源
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/poll.h>
#include <sys/wait.h>
#include <netdb.h>
#include <signal.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>

#include <arpa/inet.h>
#include <linux/if_pppopns.h>

#include <android/log.h>
#include <cutils/sockets.h>

static void log_print(int level, char *format, ...)
{
    if (level >= 0 && level <= LOG_MAX) {
        static int levels[5] = {
            ANDROID_LOG_DEBUG, ANDROID_LOG_INFO, ANDROID_LOG_WARN,
            ANDROID_LOG_ERROR, ANDROID_LOG_FATAL
        };
        va_list ap;
        va_start(ap, format);
        __android_log_vprint(levels[level], "usbmac_native", format, ap);
        va_end(ap);
    }
}

static int get_control()
{
    int i;
    if ((i = android_get_control_socket("usbmac")) == -1) {
        return -1;
    }
    log_print(DEBUG, "Waiting for control socket");
    
    int control;
    if (listen(i, 1) == -1 || (control = accept(i, NULL, 0)) == -1) {//listen to socket ,max connetion num is 1
        log_print(FATAL, "Cannot get control socket");
        exit(1);
    }
    close(i);
    fcntl(control, F_SETFD, FD_CLOEXEC);
    return control;
}

static void receive(int control, int *argc, char ***argv)
{
    static char *args[256];
    int i;
    args[0] = (*argv)[0];
    for (i = 1; i < 256; ++i) {
        unsigned char length;
        if (recv(control, &length, 1, 0) != 1) {
            log_print(FATAL, "Cannot get data length");
            exit(1);
        }
        if (length == 0xFF) {
            break;
        } else {
            int offset = 0;
            args[i] = malloc(length + 1);
            while (offset < length) {
                int n = recv(control, &args[i][offset], length - offset, 0);
                if (n > 0) {
                    offset += n;
                } else {
                    log_print(FATAL, "Cannot get data value");
                    exit(1);
                }
            }
            args[i][length] = 0;
            log_print(DEBUG, "args[%d]=%s", i, args[i]);
        }
    }
    log_print(DEBUG, "Received %d arguments", i - 1);
    *argc = i;
    *argv = args;
}


int main(int argc, char **argv)
{
    int control = get_control();
    while(1) {
        receive(control, &argc, &argv);
        if (argc -1 < 1) {
            send(control, &code[0], 1, 0);//n
            continue;
        }
    log_print(DEBUG, " %s",argv[2]);
    }
    close(control);
    signal(SIGHUP, interrupt);  
    signal(SIGINT, interrupt);
    signal(SIGTERM, interrupt);
    signal(SIGCHLD, interrupt);
    signal(SIGPIPE, SIG_IGN);
    atexit(interrupt);
    return 0;
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics