Press "Enter" to skip to content

Space4u

fopen시에 O_DIRECT와 O_SYNC의 차이

fopen 할때 옵션으로 주는데…

O_DIRECT : 캐쉬를 거치지 않고 DMA로 바로 데이터 전송하고 리턴. 데이터가 모두 전송됬는지 보장하지 않는다.

O_SYNC : 데이터가 모두 (캐쉬로) 전송됬는지 보장하고 리턴. 그러나 아직 (하드 디스크 등 출력장치에 기록되지 않고) 캐쉬에 있을 수도 있다.

O_DIRECT | O_SYNC : 캐쉬를 거치지 않고 DMA로 바로 데이터 전송하고, 완전히 전송이 끝났을 때 리턴된다. 완전하게 데이터가 출력장치에 기록되는 것을 보장한다.

O_DIRECT | O_SYNC 를 쓰는 이유 : 임베디드에서 mmap를 이 옵션으로 열어서 하드웨어 핀(GPIO)를 제어할때 쓰면 응답의 신뢰성을 높일 수 있다. 이 옵션 없이 0.001초 간격으로 신호를 10000000번 주면 캐쉬에 씌여 있다가 안나가거나… 특정 조건이 되서 한방에 나가거나… 등등 어이없는 일이 생길 수 있다.

DB같은데서는 자기네들의 알고리즘이 OS보다 성능이 좋다고 요 옵션을 써서 스스로 제어하는 경우도 있다.

참고링크 :
http://stackoverflow.com/questions/5055859/how-are-the-o-sync-and-o-direct-flags-in-open2-different-alike

시그널 숫자값

 # kill -l 
1) SIGHUP       2) SIGINT       3) SIGQUIT      4) SIGILL
5) SIGTRAP      6) SIGABRT      7) SIGBUS       8) SIGFPE
9) SIGKILL     10) SIGUSR1     11) SIGSEGV     12) SIGUSR2
13) SIGPIPE     14) SIGALRM     15) SIGTERM     16) SIGSTKFLT
17) SIGCHLD     18) SIGCONT     19) SIGSTOP     20) SIGTSTP
21) SIGTTIN     22) SIGTTOU     23) SIGURG      24) SIGXCPU
25) SIGXFSZ     26) SIGVTALRM   27) SIGPROF     28) SIGWINCH
29) SIGIO       30) SIGPWR      31) SIGSYS      34) SIGRTMIN
35) SIGRTMIN+1  36) SIGRTMIN+2  37) SIGRTMIN+3  38) SIGRTMIN+4
39) SIGRTMIN+5  40) SIGRTMIN+6  41) SIGRTMIN+7  42) SIGRTMIN+8
43) SIGRTMIN+9  44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12
47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14
51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10
55) SIGRTMAX-9  56) SIGRTMAX-8  57) SIGRTMAX-7  58) SIGRTMAX-6
59) SIGRTMAX-5  60) SIGRTMAX-4  61) SIGRTMAX-3  62) SIGRTMAX-2
63) SIGRTMAX-1  64) SIGRTMAX 

리눅스에서 ssh로 원격 파일 시스템을 마운트해보자

일단 리눅스에서 아래와 같은 패키지를 다운 받아 설치합니다.
걍 쉘에서 아래와 같이 치면 됩니다.

master@heart4u:~$ apt-get install sshfs fuse-utils
E: 잠금 파일 /var/lib/dpkg/lock 파일을 열 수 없습니다 - open (13: Permission denied)
E: Unable to lock the administration directory (/var/lib/dpkg/), are you root?

물론!!! 루트로요… 루트가 아니라면…

 master@heart4u:~$ sudo apt-get install sshfs fuse-utils 

요렇게… 하지만 이것도 권한이 있어야 한다는거….. 
안되면 root에게 부탁하세요.

패키지 목록을 읽는 중입니다... 완료
의존성 트리를 만드는 중입니다
상태 정보를 읽는 중입니다... 완료
다음 새 패키지가 전에 자동으로 설치되었지만 더 이상 필요하지 않습니다:
  diff
이들을 지우기 위해서는 'apt-get autoremove'를 사용하십시오.
다음 패키지를 더 설치할 것입니다:
  libfuse2 mount
제안하는 패키지:
  nfs-common
다음 새 패키지를 설치할 것입니다:
  sshfs
다음 패키지를 업그레이드할 것입니다:
  fuse-utils libfuse2 mount
3개 업그레이드, 1개 새로 설치, 0개 지우기 및 198개 업그레이드 안 함.
379k바이트 아카이브를 받아야 합니다.
이 작업 후 147k바이트의 디스크 공간을 더 사용하게 됩니다.
계속 하시겠습니까 [Y/n]? y
받기:1 http://kr.archive.ubuntu.com/ubuntu/ lucid-updates/main mount 2.17.2-0ubuntu1.10.04.2 [175kB]
받기:2 http://kr.archive.ubuntu.com/ubuntu/ lucid-updates/main fuse-utils 2.8.1-1.1ubuntu3.1 [22.0kB]
받기:3 http://kr.archive.ubuntu.com/ubuntu/ lucid-updates/main libfuse2 2.8.1-1.1ubuntu3.1 [141kB]
받기:4 http://kr.archive.ubuntu.com/ubuntu/ lucid/main sshfs 2.2-1build1 [40.8kB]
내려받기 379k바이트, 소요시간 2s (166k바이트/초)
(데이터베이스 읽는중 ...현재 74042개의 파일과 디렉토리가 설치되어 있습니다.)
mount 2.17.2-0ubuntu1 패키지를 대체할 준비하는 중입니다 (.../mount_2.17.2-0ubuntu1.10.04.2_i386.deb 사용) ...
대체되는 mount 패키지를 푸는 중입니다 ...
man-db에 대한 트리거를 처리하는 중입니다 ...
mount (2.17.2-0ubuntu1.10.04.2) 설정하는 중입니다 ...
(데이터베이스 읽는중 ...현재 74042개의 파일과 디렉토리가 설치되어 있습니다.)
fuse-utils 2.8.1-1.1ubuntu2 패키지를 대체할 준비하는 중입니다 (.../fuse-utils_2.8.1-1.1ubuntu3.1_i386.deb 사용) ...
대체되는 fuse-utils 패키지를 푸는 중입니다 ...
libfuse2 2.8.1-1.1ubuntu2 패키지를 대체할 준비하는 중입니다 (.../libfuse2_2.8.1-1.1ubuntu3.1_i386.deb 사용) ...
대체되는 libfuse2 패키지를 푸는 중입니다 ...
전에 선택하지 않은 sshfs 패키지를 선택합니다.
sshfs 패키지를 푸는 중입니다 (.../sshfs_2.2-1build1_i386.deb에서) ...
man-db에 대한 트리거를 처리하는 중입니다 ...
libfuse2 (2.8.1-1.1ubuntu3.1) 설정하는 중입니다 ... 
fuse-utils (2.8.1-1.1ubuntu3.1) 설정하는 중입니다 ...
udev active, skipping device node creation.
update-initramfs: deferring update (trigger activated) 
sshfs (2.2-1build1) 설정하는 중입니다 ...
libc-bin에 대한 트리거를 처리하는 중입니다 ...
ldconfig deferred processing now taking place
initramfs-tools에 대한 트리거를 처리하는 중입니다 ...
update-initramfs: Generating /boot/initrd.img-2.6.32-25-generic-pae 


요렇게 줄줄줄줄 다 설치가 됩니다.
그러면 도움말을 함 볼까요?

master@heart4u:~$ sshfs -h
usage: sshfs [user@]host:[dir] mountpoint [options]
general options:
    -o opt,[opt...]        mount options
    -h   --help            print help
    -V   --version         print version 
 
SSHFS options:
    -p PORT                equivalent to '-o port=PORT'
    -C                     equivalent to '-o compression=yes'
    -F ssh_configfile      specifies alternative ssh configuration file
    -1                     equivalent to '-o ssh_protocol=1'
    -o reconnect           reconnect to server
    -o sshfs_sync          synchronous writes
    -o no_readahead        synchronous reads (no speculative readahead)
    -o sshfs_debug         print some debugging information
    -o cache=YESNO         enable caching {yes,no} (default: yes)
    -o cache_timeout=N     sets timeout for caches in seconds (default: 20)
    -o cache_X_timeout=N   sets timeout for {stat,dir,link} cache
    -o workaround=LIST     colon separated list of workarounds
             none             no workarounds enabled
             all              all workarounds enabled
             [no]rename       fix renaming to existing file (default: off)
             [no]nodelaysrv   set nodelay tcp flag in sshd (default: off)
             [no]truncate     fix truncate for old servers (default: off)
             [no]buflimit     fix buffer fillup bug in server (default: on)
    -o idmap=TYPE          user/group ID mapping, possible types are:
             none             no translation of the ID space (default)
             user             only translate UID of connecting user
    -o ssh_command=CMD     execute CMD instead of 'ssh'
    -o ssh_protocol=N      ssh protocol to use (default: 2)
    -o sftp_server=SERV    path to sftp server or subsystem (default: sftp)
    -o directport=PORT     directly connect to PORT bypassing ssh
    -o transform_symlinks  transform absolute symlinks to relative
    -o follow_symlinks     follow symlinks on the server
    -o no_check_root       don't check for existence of 'dir' on server
    -o password_stdin      read password from stdin (only for pam_mount!)
    -o SSHOPT=VAL          ssh options (see man ssh_config) 
 
FUSE options:
    -d   -o debug          enable debug output (implies -f)
    -f                     foreground operation
    -s                     disable multi-threaded operation
    -o allow_other         allow access to other users
    -o allow_root          allow access to root
    -o nonempty            allow mounts over non-empty file/dir
    -o default_permissions enable permission checking by kernel
    -o fsname=NAME         set filesystem name
    -o subtype=NAME        set filesystem type
    -o large_read          issue large read requests (2.4 only)
    -o max_read=N          set maximum size of read requests
    -o hard_remove         immediate removal (don't hide files)
    -o use_ino             let filesystem set inode numbers
    -o readdir_ino         try to fill in d_ino in readdir
    -o direct_io           use direct I/O
    -o kernel_cache        cache files in kernel
    -o [no]auto_cache      enable caching based on modification times (off)
    -o umask=M             set file permissions (octal)
    -o uid=N               set file owner
    -o gid=N               set file group
    -o entry_timeout=T     cache timeout for names (1.0s)
    -o negative_timeout=T  cache timeout for deleted names (0.0s)
    -o attr_timeout=T      cache timeout for attributes (1.0s)
    -o ac_attr_timeout=T   auto cache timeout for attributes (attr_timeout)
    -o intr                allow requests to be interrupted
    -o intr_signal=NUM     signal to send on interrupt (10)
    -o modules=M1[:M2...]  names of modules to push onto filesystem stack
    -o max_write=N         set maximum size of write requests
    -o max_readahead=N     set maximum readahead
    -o async_read          perform reads asynchronously (default)
    -o sync_read           perform reads synchronously
    -o atomic_o_trunc      enable atomic open+truncate support
    -o big_writes          enable larger than 4kB writes
    -o no_remote_lock      disable remote file locking
Module options:
[subdir]
    -o subdir=DIR           prepend this directory to all paths (mandatory)
    -o [no]rellinks         transform absolute symlinks to relative
[iconv]
    -o from_code=CHARSET   original encoding of file names (default: UTF-8)
    -o to_code=CHARSET      new encoding of the file names (default: UTF-8) 

아… 모르겠다… ㅡㅡ;;;;

usage: sshfs [user@]host:[dir] mountpoint [options]

맨 위에 휘리릭 올라가 버려서 허탈한거… 저거만 중요한거네요… ㅋ

됫꼬!!! 마운트 해봅시다.

마운트할 디렉토리를 하나 만들고요 mkdir mntssh

마운트를 시도합니다.

sshfs myaccount@sshserver.co.kr: ./mntssh


요기서 도메인 뒤에 반드시 : 를 붙여줘야 합니다.

계속할꺼냐고 물어보면 yes 라고 다 쳐주시고

계정의 비밀번호를 넣습니다.

그런 다음에 마운트 포인트된 디렉토리를 ls 로 뒤져봅니다.

정상적으로 마운트 되면 파일 내용이 보일꺼에요~~~

master@heart4u:~$ mkdir mntssh
master@heart4u:~$ sshfs myaccount@sshserver.co.kr: ./mntssh
The authenticity of host 'sshserver.co.kr (211.xxx.xxx.44)' can't be established.
RSA key fingerprint is XX:XX:XX:XX:XX:YY:YY:YY:YY:YY:ZZ:ZZ:ZZ:ZZ:ZZ:ZZ
Are you sure you want to continue connecting (yes/no)? yes
myaccount@sshserver.co.kr's password:
master@heart4u:~$ ls mntssh
public_html
master@heart4u:~$


끗!!!


끗!! 내기 전에 이거까지…

끝내기 전에 … ㅡㅡ;;;;;

master@heart4u:~$ fusermount -u mntssh
master@heart4u:~$ ls mntssh
master@heart4u:~$


마운트를 했으면 해제도 해야죠???? 이거 모르면 해멤니다….. ㅋ

리눅스에서 윈도우 공유폴더를 마운트 해 보자.

다음과 같이 쓰면 된다.

sudo mount -t cifs -o username=yjlee,uid=1000,gid=0,iocharset=utf8,codepage=cp949 //192.168.100.12/ShareFD ./sharefd/

sudo 는 루트권한으로 실행해 보자~
mount 는 마운트 하겠다는 명령어
-t cifs 는 파일 시스템 이름인데 윈도우의 공유폴더를 연결할때는 이렇게 한다.
-o 뒤에는 옵션이 붙는다.  각 옵션은 ,로 구분한다. 로그인이 필요한 경우 username으로 윈도우 컴의 로그인 아이디를 적어주었다. uid와 gid는 마운트된 영역의 유저아이디와 그룹아이디를 설정하는데 마운트 하는 사용자의 번호를 사용하면 되겠다. ls -lan (n옵션이 숫자로 유져아이디와 그룹아이디를 보여준다)로 조회하면 나온다. 그다음 입출력문자셋이 utf8이고 코드페이지가 cp949로 설정하여 공유폴더의 한글이 정상적으로 표시되게 한다.
//192.168.100.12/ShareFD 는 IP에 공유된 폴더 이름
./sharefd 는 마운트될 리눅스 상의 디렉토리

정상적으로 마운트 되면 ./sharefd 안을 살펴보면 공유된 폴더의 내용이 보일 것이다.

Segmentation fault 뜰때~ 돌려보자~

메모리 깨먹을 때 Segmentation fault 가 작렬하지요…

배열의 첨자를 벗어나서 접근하거나 포인터를 할당된 메모리를 넘어서 접근할때 나지요.

free에서 죽는 경우가 많고요.

주의할점은 malloc으로 strlen만큼 메모리를 잡고 sprintf를 하면 절대!!!!!! 안됩니다. 
sprintf는 뒤에 무조건 NULL을 하나 더 넣어주기 때문에 strlen보다 1 크게 잡아줘야 합니다.

또.. 

*** glibc detected *** free():invalid point

라는 메시지를 툭~~~ 던지고 몇페이지나 되는 데이터가 주루루루루룩~ 올라가는 경우가 있습니다.
요넘도 비정상적인 메모리 프리가 체크되면 뜨는건데요…

Linux libc 5.4.23이후와 GNU libc 2.x 버전은 환경 변수로 malloc을 조정할 수 있습니다.
쉘에서 export MALLOC_CHECK_=3 해주시면 에러 메시지를 출력하고 종료해 줍니다. 설정 값은 0~3

0 : 아무것도 하지 않고 그냥 프로그램 동작…. 프리하는 순간엔 죽겠죠??? 언젠가 맛팅이 가겠죠…
1 : 에러 메시지 출력
2 : 아무런 메시지 없이 프로그램 종료
3 : 에러 메시지 출력하고 프로그램 종료

긍게 2, 3을 해서 메모리 손상이 감지 됬을때 서 버리는게 낫겠죠? 메시지까지 출력해 준다면(3) 최고겠구요…

쉽게 문제의 코드를 찾는 방법은 valgrind 라는 프로그램을 쓰면됩니다.
정말 찾아내는 순간 쪽팔려서 얼굴이 발그레진다능… ㅋㅋㅋ

valgrind 자기가만든프로그램

요렇게 실행하면 어디쯤에서 메모리를 깨먹는지 대충 알려줍니다…. 영어루… ㅡㅡ;

apt-get instll valgrind apt-get install valgrind 를 하면 우분투에선 걍 설치해주겠죠???? 아님 말구… ^^