본문 바로가기

Programming/Linux_Platform

mmap (user space)의 MAP_ANONYMOUS 에 대해서... mmap은 보통 file이나 kernel이 alloc한 memory를 user space에서 remap해서 VA로 접근하기 위해 사용하지만, MAP_ANONYMOUS 로 사용할 경우는, addr=0, fd=-1로 설정하게 된다. 어떤 case에서 이러한 mapping을 사용하는지 보자. 우선, MAP_ANONYMOUS로 할당한다고 해도, user application 상에서 이 memory를 read write 하는데는 아무런 문제가 없다는 것을 미리 알아두자. http://jake.dothome.co.kr/user-virtual-maps-mmap2/ 어떠한 파일하고도 연결되지 않고 0으로 초기화된 영역. fd는 무시되지만 어떤 경우에는 -1이 요구된다. offset는 0으로 한다. MAP_SHARED와.. 더보기
systemd log를 dmesg와 console에 enable 하는 방법 참고 : https://www.freedesktop.org/software/systemd/man/journald.conf.html "/etc/systemd/journald.conf" 파일에 Forwardtokmsg, ForwardToConsole 를 yes로 변경. --> ForwardToSyslog=yes ForwardToKMsg=yes ForwardToConsole=yes 더보기
taskset : user process 를 특정 cpu에서 동작하도록 하기 원문 : http://coffeenix.net/board_view.php?bd_code=1702 ■ Taskset 이란? TaskSet은 프로세스가 사용할 CPU(CPU affinity) 를 보여주거나 지정해준다. ■ 사용 방법 taskset [options] [mask | list ] [pid | command [arg]...] mask는 Process가 사용할 CPU 값을 나타내며 16진수로 표현이 된다. 0x00000001 는 0번 프로세스(CPU)의 사용을 나타내며 0x00000003 는 0번과 1번 프로세스(CPU)의 사용을 나타내며 0xFFFFFFFF 는 모든 프로세스(CPU)의 사용을 나타냅니다.(0 ~ 31번..) 물론, mask를 프로세서(CPU)의 숫자로 표현할 수도 있다. mask를 .. 더보기
[systemd-analyze] systemd debugging & analyze method http://manpages.ubuntu.com/manpages/bionic/man1/systemd-analyze.1.html Ubuntu Manpage: systemd-analyze - Analyze and debug system manager Powered by the Ubuntu Manpage Repository, file bugs in Launchpad © 2019 Canonical Ltd. Ubuntu and Canonical are registered trademarks of Canonical Ltd. manpages.ubuntu.com 어떤 daemon 이 systemd 의 초기화를 느리게 하고 있다면, 아래 command로 확인이 가능하다. systemd-analyze blame 더보기
SetUID / SetGID Special File Permissions 출처 : http://kin.naver.com/qna/detail.nhn?d1id=1&dirId=10302&docId=128463841&page=1#answer1안녕하세요.. 답변이 될지 모르겠으나 Set UID / Set GID에 대해 설명드리겠습니다. Set UID는 chmod 4000 권한으로 실행되며, Set GID는 chmod 2000 권한으로 실행합니다.둘다 설정하시려면 6000 권한으로 설정 하시면 됩니다.( 여기서 000은 일반 퍼미션 이며, 파일 실행권한은 꼭 가지고 있어야 합니다. ) 파일 퍼미션 설정이 기본적으로 rwx/rwx/rwx 로 이런 식으로 설정이 되나,Set UID설정 시 rws/rwx/rwx로 변경.Set GID설정 시 rwx/rws/rwx로 변경.둘다 설정 시 rws/r.. 더보기
The result of getmntent() function The example codeFILE* fp = setmntent("/proc/mounts", "r"); if (fp == NULL) { ALOGE("Error opening /proc/mounts: %s", strerror(errno)); return -errno; } // Some volumes can be stacked on each other, so force unmount in // reverse order to give us the best chance of success. std::list toUnmount; mntent* mentry; while ((mentry = getmntent(fp)) != NULL) { if (strncmp(mentry->mnt_dir, path, path_len).. 더보기
signal 7 (SIGBUS), code 1 (BUS_ADRALN), fault addr 참고 URL : http://stackoverflow.com/questions/3246441/what-does-bus-adraln-invalid-address-alignment-error-meanshttp://www.badayak.com/3302 일반적으로 point 변수에 잘못된 값이 들어가 있을 경우는 null point exception 이나 다른 error 가 발생할 것이지만, 변수 자체가 invalid address alignment error 가 발생했다는 것은, 다른 수행에 의해서 변수 값 영역이 침범당했음을 의미한다. 아래 아티클의 작성자는 원인을 찾지 못했지만,http://www.badayak.com/3302아마 원인은 아래 (1) 을 수행할때 f_value3 영역이 침범당했기 때문일 것.. 더보기
makedev makedev (3) #include dev_t makedev(unsigned int maj, unsigned int min); unsigned int major(dev_t dev); unsigned int minor(dev_t dev); linux device driver 는 major num 와 minor num 로 관리되는데 이 두 number 를 하나의 type 으로 정의한 것이 dev_t 이다. makedev system call 은 실제 '/dev' 에 device node 를 생성하는 것이 아닌,단순히 major, minor number 를 조합해서 dev_t type 을 생성해 주는 역할이다. makedev (8) 반면에 makedev 실행 파일은 실제로 '/dev' 에 주어진 major .. 더보기
파일의 속성을 check 하는 코드 - fstatat, fstat, stat, lstat 아래는 dirfd 아래에 asecName 이라는 파일이 regular file인지 check 하는 코드 ex) dirfd = "/mnt/secure/asec/" asecName = "1234" 이면 /mnt/secure/asec/1234 라는 regular file 이 있는지 check 해 준다. struct stat sb; bool ret = (fstatat(dirfd, asecName, &sb, AT_SYMLINK_NOFOLLOW) == 0) && S_ISREG(sb.st_mode); http://www.tutorialspoint.com/unix_system_calls/stat.htm The following POSIX macros are defined to check the file type usi.. 더보기
find PID as process name and send signal using shell script #!/system/bin/shecho "sigquit.system_server.sh: start" > /dev/kmsgecho "sigquit.system_server.sh: start"sleep 10.0str=""echo "sigquit.system_server.sh: delay finish" > /dev/kmsgecho "sigquit.system_server.sh: delay finish"while [ "$str" = "" ]; do str=`ps | grep system_server` sleep 0.1donepid=${str:10:4}echo "sigquit.system_server.sh: kill -3 ${pid}" > /dev/kmsgecho "sigquit.system_server.sh: k.. 더보기
android adb 에서 sh : shell script file 이 실행 안될때 실행법 # sh ./sigquit.system_server.sh & or # /system/bin/sh ./sigquit.system_server.sh & 아래와 같이 error 가 날때는 root@gracelte:/data/local/tmp # sh ./sigquit.system_server.sh & [1] 13625'oot@gracelte:/data/local/tmp # ./sigquit.system_server.sh[3]: sleep: syntax error: Invalid argument '10.0./sigquit.system_server.sh[6]: syntax error: 'while' unmatched [1] + Done (1) sh ./sigquit.system_server.sh Ubunt.. 더보기
get pid by process name - example source code (예제 코드) 원문 : https://phoxis.org/2013/09/13/find-process-ids-of-a-running-process-by-name/ 이름으로 pid 를 찾아내는 예제 #include #include #include #include #include #include /* checks if the string is purely an integer * we can do it with `strtol' also */int check_if_number (char *str){ int i; for (i=0; str[i] != '\0'; i++) { if (!isdigit (str[i])) { return 0; } } return 1;} #define MAX_BUF 1024#define PID_LIST_BL.. 더보기
logging "linux platform log" without usb connection logging "linux platform log" without usb connectionusb 연결없이 platform log 계속해서 받기 1. connecting adb shell2. type thislogcat > /sdcard/log/name.log &3. adb shell stop adbd4. test start to get log5. adb pull /sdcard/log/ 더보기
file open 시 fd 번호 부여 방식 하나의 process 에서 한 파일을 연속으로 open 할때 fd number 부여 방식 - 이전에 3 이라는 fd 숫자를 써서 open 하고 close 를 함.- 다음 open 때는 fd 로 3이 부여 된다.- 따라서 file close 이후에는 항상 fd 에 -1 을 저장하는 것이 중요함. test code#include //#include #include #include #include #include #include #include // O_WRONLY#include // strlen() #define BUFF_SIZE 1024 int main(){ char buff_r[BUFF_SIZE], buff_w[BUFF_SIZE]; int fd[10];int rst;int fd_num; for(int i.. 더보기
kill parent and child process sametime #include //#include #include #include #include #include #include int main(int argc, char *argv[]){// signal(SIGALRM, timer_handler); // add handler about sigalrm pid_t pid, child_pid; int rc=0; pid = fork(); if (pid == 0){ // childprintf("[child] I'm child(%d)\n", getpid()); //char *argvs[] = {~~~~~~~, (char *)0}; //return execv(~~~~~~~~~); // run other program pid_t ppid = getppid();pid_t pgid .. 더보기
TEMP_FAILURE_RETRY 이따금 Android code 에서 TEMP_FAILURE_RETRY mecro 를 사용한 function 들을 볼 수 있다.하지만, 이 매크로는 매우 위험할 수 있다.return true 가 발생하지 않는다면, 호출한 thread 는 영원히 loop 속으로 빠질 수 있다. 따라서 이 mecro 가 포함된 function 을 호출할때는 주의하는것이 좋다. 28#ifndef TEMP_FAILURE_RETRY 29/* Used to retry syscalls that can return EINTR. */ 30#define TEMP_FAILURE_RETRY(exp) ({ \ 31 typeof (exp) _rc; \ 32 do { \ 33 _rc = (exp); \ 34 } while (_rc == -1 && .. 더보기
[linux] openat / open 의 차이점 출처 : http://pinocc.tistory.com/140 [linux] openat / open 의 차이점 지금은 확실히 개념이 들어오진 않는다.일단 스크랩 후 좀 더 자새히... open SYNOPSIS #include #include #include int open(const char *pathname, int flags); int open(const char *pathname, int flags, mode_t mode); int creat(const char *pathname, mode_t mode); openatSYNOPSIS #include int openat(int dirfd, const char *pathname, int flags); int openat(int dirfd, const .. 더보기
Android init.rc 분석 기본 문법http://www.dreamy.pe.kr/zbxe/CodeClip/164851 설명http://egloos.zum.com/shadowxx/v/10770478http://blog.naver.com/PostView.nhn?blogId=multiedit&logNo=40147752143 예제http://forum.falinux.com/zbxe/index.php?mid=android&sort_index=readed_count&order_type=asc&document_srl=781528 class name 을 등록하고 아래와 같이 class 를 start stop 시킬 수 있다.즉, class_start 를 호출하면 해당 class name 을 등록한 모든 service 들이 시작된다.. 더보기
fstab & partition images type 의 emmc -> 는 row data 를 뜻함.즉, filesystem 없이 blk 단위로 read/write 하는 partition 임. # /dev/block/platform/msm_sdcc.1/by-name/boot /boot emmc default recoveryonly/dev/block/platform/msm_sdcc.1/by-name/recovery /recovery emmc default recoveryonly/dev/block/platform/msm_sdcc.1/by-name/system /system ext4 default recoveryonly/dev/block/platform/msm_sdcc.1/by-name/userdata /data ext4 default wait,leng.. 더보기
linux command : stat, fstat, lstat http://s2kiess.blog.me/220139796462 stat : 파일경로를 가지고 파일 속성을 가지고 온다.fstat : 파일 디스크립터를 가지고 파일 속성을 가지고 온다. 심볼릭 링크의 경우 원본 파일의 속성을 가지고 온다.lstat : fstat 과 동일하나, 심볼링 링크일 경우 링크 파일의 속성을 가지고 온다. The usage of "stat" on arm linux # statusage: stat [-f] [-c FORMAT] FILE... Display status of files or filesystems. -f display filesystem status instead of file status-c Output specified FORMAT string instead of d.. 더보기
헷갈리는 c string 함수들 정리중... strstr은 문자열 중에서 특정 문구를 찾아 그 위치를 반환해 주는 함수특히, 포함된 문자열을 찾는데 유용하다. (strcmp 를 사용하면 안된다 !!) /*strstr */char * strstr(const char * str1, const char * str2); 참조 : http://tapito.tistory.com/313 1. strcat - strcat (string concatenation)은 문자열 2개를 이어 붙이는 역할을 해주는 함수이다. 예컨대, "Love"와 "You"를 합치면 LoveYou가 될 것이다. 이처럼 두개의 문자열을 합쳐주는 함수가 strcat 이다. 이 함수의 사용방법과 내부적인 결과를 자세히 살펴보자. 먼저 함수의 모양을 알아보자. 함수.. 더보기
epoll 에 대한 한국어 설명 poll 이나 select 의 비 효율성을 해결한 새로운 기능. http://vovheas104.blog.me/220485326114 http://cafe.naver.com/newchany/87 더보기
close_on_exec static __inline__ int adb_socketpair( int sv[2] ){ int rc; rc = unix_socketpair( AF_UNIX, SOCK_STREAM, 0, sv ); if (rc < 0) return -1; close_on_exec( sv[0] ); close_on_exec( sv[1] ); return 0;} static __inline__ void close_on_exec(int fd){ fcntl( fd, F_SETFD, FD_CLOEXEC );} #include int execve(const char *filename, char *const argv[], char *const envp[]);함수를 호출하면 기본적으로는 file descriptor 가 open 된 .. 더보기
socketpair() 출처 : http://osr507doc.sco.com/en/netguide/dusockD.socketpairs_codetext.html socketpair: read / write 가 가능한 한쌍의 socket 을 open 한다. 예제 Socketpair sample code (UNIX only)The following example illustrates the use of socketpairs, which are a slight generalization of pipes used for two-way stream communication. Because socketpairs are an extension of pipes, their use resembles that of pipes rather than.. 더보기
linux signals 출처 : http://fehead.tistory.com/146 SIGPIPE파이프가 끊겼을 경우 발생하는 signalhttp://blog.naver.com/PostView.nhn?blogId=hyungii&logNo=130081645365 * 파이프깨짐?소켓은 프로세스간 통신 메카니즘의 확장으로 볼 수 있습니다.전형적인 유닉스의 프로세스간통신(IPC라고 하지요) 메카니즘은 파이프입니다.이러한 관습(?)에 힘입어, 소켓에서도 그 연결이 끊기는 경우 파이프가 끊겼다느니, 깨졌다느니, broken pipe등의 메시지를 사용합니다.파이프깨짐은 바로 통신의 종결을 의미합니다. 통신이 끊김은 어떻게 감지하는가? 보통 3가지 방법이 있을 수 있습니다.1) 상태검사 : 소켓도 파일로 간주하므로, 파일의 상태정보를 읽어.. 더보기
linux stand out 을 file 에 logging 하기 static const char *TEMPORARY_LOG_FILE = "/tmp/recovery.log"; redirect_stdio(TEMPORARY_LOG_FILE); static void redirect_stdio(const char* filename) { // If these fail, there's not really anywhere to complain... freopen(filename, "a", stdout); setbuf(stdout, NULL); freopen(filename, "a", stderr); setbuf(stderr, NULL);} 더보기
linux namespace 각각의 process 가 가지고 있는 mount set다른 FS namespace 를 가지고 있는 process 는 서로 다른 mount information 을 가지고 있다.각 process 의 proc 의 ns 에서 FS namespace 를 확인 할 수 있다. root@klte:/proc/7532 # ls -al /proc/7939/ns lrwxrwxrwx bluetooth bluetooth 2015-01-02 11:09 mnt -> mnt:[4026534520]lrwxrwxrwx bluetooth bluetooth 2015-01-02 11:09 net -> net:[4026533490]root@klte:/proc/7532 # ls -al /proc/7532/nslrw.. 더보기
Android log command, logwrapper 출처 : http://elinux.org/Android_Logging_System Android log message 를 만든다. log -p e -t onegun test message25402 01-08 09:27:26.210 15852 15852 E onegun : test message Process 가 출력하는 stdout 이나 stderr 즉, terminal 로 출력될 내용들을 android log 로 보내서 로깅되도록 한다. logwrapper -x ./test_program_name -testprogram_argstag : binarypriority : LOG_INFO 더보기
logcat 사용법 정리 [adb] logcat [] ... [] ... The following table describes the logcat command line options: -c Clears (flushes) the entire log and exits. 전체로그를 삭제하고 빠져나옵니다. -d Dumps the log to the screen and exits. 저장된 로그를 화면에 출력하고 종료한다. -f Writes log message output to . The default is stdout. -g Prints the size of the specified log buffer and exits. 로그버퍼의 사이즈를 출력 -n Sets the maximum number of rotated logs to . T.. 더보기
wrtie 비교 O_DIRECT and no-delay-alloc mount option - O_DIRCET optionopen 함수에 주는 flag - no-delay-alloc optionfile system mount option : file write 를 보통 지연시켜서 하는데 이기능을 사용하지 않음. umount /cache 일반적인 mount 명령어mount -t ext4 /dev/block/mmcblk0p27 /cache no delay alloc mount 명령어mount -t ext4 -o nodelalloc /dev/block/mmcblk0p27 /cache test source code 하기 파일에서 O_DIRECT 주석을 풀어주면 O_DIRECT 로 동작함.간단히 input file 을 open 하여 내용을 읽고 output 파일에 write 하는 예제임. 결과를 mos.. 더보기