ubuntu 在 R40e 上 還有 Debian 在 Sempron 2600 上

2011年1月18日 星期二

socket interface syscomamnd daemon

follow 前篇,為了執行一堆有權限限制的 command,所以寫一個 syscommandd: #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <string.h> #define FDNAME "/data/syscommandfd" int main(int argc,char *argv[]) { int sock,msgsock,rval; struct sockaddr_un server; char buf[1024]; int runserver=3; int sysexitcode; unlink(FDNAME); sock = socket(AF_UNIX, SOCK_STREAM,0); if(sock<0) { perror("opening stream socket"); exit(1); } server.sun_family = AF_UNIX; strcpy(server.sun_path, FDNAME); if (bind(sock,(struct sockaddr *)&server, sizeof(struct sockaddr_un))) { perror("binding stream socket"); exit(1); } printf("socket has name:%s\n",server.sun_path); listen(sock,5); do { msgsock = accept(sock,0,0); if (msgsock == -1) perror("accept"); else do { bzero(buf,sizeof(buf)); if ((rval = read(msgsock, buf, 1024))<0) perror("reading stream message"); else if(rval>0) { printf("rcv : %s\n",buf); sysexitcode = system(buf); printf("sys exit code: %d\n",sysexitcode); } } while (rval > 0); runserver --; close(msgsock); } while(runserver); close(sock); unlink(FDNAME); printf("syscommandd..\n"); return 0; } Android.mk LOCAL_PATH:= $(call my-dir) include $(CLEAR_VARS) LOCAL_SRC_FILES := syscommandd.c LOCAL_MODULE := syscommandd LOCAL_CFLAGS += -lpthread -lrt LOCAL_MODULE_TAGS := tests include $(BUILD_EXECUTABLE) 測試程式: c : #include <sys/types.h> #include <sys/socket.h> #include <sys/un.h> #include <stdio.h> int main(int argc,char *argv[]) { int sock; struct sockaddr_un server; char buf[1024]; if (argc < 3) { printf("usage:%s <pathname> <msg-to-server>", argv[0]); exit(1); } sock = socket(AF_UNIX, SOCK_STREAM, 0); if (sock < 0) { perror("opening stream socket"); exit(1); } server.sun_family = AF_UNIX; strcpy(server.sun_path, argv[1]); if (connect(sock, (struct sockaddr *) &server, sizeof(struct sockaddr_un)) < 0) { close(sock); perror("connecting stream socket"); exit(1); } if (write(sock, argv[2], strlen(argv[2])) < 0) perror("writing on stream socket"); close(sock); return 0; } Android Code,使用: public static void writeSocket(String shellcommand) throws IOException { LocalSocket sender = new LocalSocket(); sender.connect(new LocalSocketAddress("/data/syscommandfd",LocalSocketAddress.Namespace.FILESYSTEM)); sender.getOutputStream().write(shellcommand.getBytes()); sender.getOutputStream().close(); } 執行就: writeSocket("touch aa");

沒有留言:

標籤

網誌存檔