1. Android build 스크립 수정하기

.build/core/main.mk

파일을 여시면

75 ifeq ($(BUILD_OS),linux)
76 build_arch := $(shell uname -m)
77 ifneq (64,$(findstring 64,$(build_arch)))
78 $(warning ************************************************************)
79 $(warning You are attempting to build on a 32-bit system.)
80 $(warning Only 64-bit build environments are supported beyond froyo/2.2.)
81 $(warning ************************************************************)
82 $(error stop)
83 endif
84 endif

이 부분을 주석 처리 해주시고 저장 후 파일 닫으시면 됩니다.

    2. Android 스크립 수정하기

우선 Gingerbread 소스를 안드로이드 git에서 받으신 뒤에 

root 디렉토리 기준에서

./external/clearsilver/cgi/Android.mk
./external/clearsilver/java-jni/Android.mk
./external/clearsilver/util/Android.mk
./external/clearsilver/cs/Android.mk

위 파일을 여신 뒤

# LOCAL_CFLAGS += -m64
# LOCAL_LDFLAGS += -m64

부분에 있는 64를 32로 변경 하신 뒤 저장 하시면 됩니다.

저장이 끝나면 root 디렉토리에서 make -j3 를 하시면 됩니다.

에뮬레이터를 만들고 싶으신 경우엔 make -j3 로 빌드를 다 하고 난 뒤

make sdk 를 치시면 됩니다.
개발자로써 윈도우에서 마음에 드는 툴이 있다면 Source Insight가 있다. 요즘에 보면 많이 개발자들이 Source Insight를 이용하여 대량의 소스를 분석하고 편집하고 ~~ 뭐 개발하는데 쓰는거 같다.

리 눅스를 쓰면서 이와 같은 것이 없을까 하면 많은 리눅스 개발자들은 vi +ctags + cscope면 된다고 한다. 물론 이 툴들의 성능은 정말 부족한것이 없다. 하지만 단점이라고 하자면 익숙하게 사용하기 위한 시간과 노력을 투자해야 한다는 것이다. ㅎㅎ 개인차가 있을 수도 있지만...,,,

그래서 찾아보니 비슷한 KScope가 있지 않은가 KDE 기반에 source 분석툴로써 백그라운드로 cscope를 이용한다. 처음에 딱 보았을때는 정말 Source insight가 무척 많이 닮아 있었다.

사용자 삽입 이미지

여러가지 기능이 있지만 소스를 분석하다 보면 함수의 호출 관계를 좀더 간략하게 보기를 원할때가 있다. KScope에서는 Call Graph를 이용하여 이를 도식화 하여 보여 준다.
사용자 삽입 이미지

한가지 단점이 있다면 내장 에디터가 없어서 KScope에서 자체적으로 소스의 편집은 할수가 없다. 그래서 그냥 vim을 이용하여 소스는 편집하고 KScope를 이용하여 전체적으로 소스의 구조를 관찰하면 될거 같다.

개 발의 대부분이 처음부터 새로 만드는 것이라면 모르겠지만 기존에 구축된 큰 시스템에서 일부분을 추가하거나 수정해야 한다면 KScope를 이용하여 프로젝트를 생성해서 소스의 분석을 하면서 편집이나 소스 작성은 자신만의 소스 Edit툴을 이용하여 하면 될듯 하다.

한번쯤 사용해 보면 리눅스에서 괜찮은 툴인듯 하다.
제 경우 32bits 머신에서 빌드하려다보니, 64bits 머신을 사용하라는 에러가 발생하네요..

32bits 머신에서 빌드하는 방법을 구글링해봤습니다. 덕분에 잘 빌드되네요.

1) /build/core/main.mk 수정
-ifneq (64,$(findstring 64,$(build_arch))) 
+ifneq (i686,$(findstring i686,$(build_arch)))

2) /external/clearsilver/ 내 Android.mk 수정
-LOCAL_CFLAGS += -m64 

참조URL: http://groups.google.com/group/android-platform/browse_thread/thread/b0bb991131589363


본 : http://www.kandroid.org/board/board.php?board=androidsource&command=body&no=72


일단 공식 홈페이지는 아래와 같다.

 

http://www.android-x86.org/

 

초기에 비하면 꽤 많은 진척이 있는 것 같다.

Virtual Box로도 동작 확인이 가능하며, Eclair, Froyo, Ginger-Bread 까지 빠르게 포팅 작업이 이루어 지고 있는 것 같다.

 

테스트 플랫폼도 EeePC, Samsung Q1U, Viliv S5, Lenovo ThinkPad x61 Tablet, ViewSonic ViewPad 10 등이 있다.

 

넷북에서의 사용을 목적으로 하기 때문에 기존 안드로이드와 다르게 추가된 내용은 다음과 같다.

 

- Wifi 와 Ethernet 지원

- Mouse cursor/wheel 지원

- native resolution 지원 (800x480 과 1024x600 지원)

- Proxy setting 지원

- Mplayer 포팅

- External storage auto mount support (Virtual Box로는 아무 변화가 없는 듯)

- External monitor support (해야하는 일로 되어 있어서 좀 더 확인해 봐야 할듯)

 

Virtual Box로는 OpenGL 지원이 제대로 되는지 모르겠다. Live Wallpaper 설정시, 일부는 정상 동작하고 일부는 동작이 조금 이상하게 나온다.

 

Atom 기반으로 되어 있기 때문에 최적화나 시스템 부하는 고려하지 않는 점이 있어서 ARM 기반으로 포팅시에는 주의가 필요하다.

 

코드 받으려면 다음과 같이 한다.

 

$repo init –u git://git.android-x86.org/manifest.git –b $branch
$repo sync

 

branch 명은 donut-x86, eclair-x86, froyo-x86, gingerbread-x86 이다.

오늘 해 볼 작업은 WebView 입니다. 웹기반 어플리케이션이라고 보면 되고 완성될 화면은 아래와 같습니다.

Daum의 모바일 웹페이지 프론트 페이지입니다. 맨 아래 하단에는 버튼을 두어서 원하는 곳으로 이동도 해 볼 겁니다.


 

Daum의 모바일용 웹페이지를 호출한 화면입니다.

웹브라우져 객체를 담기 위해 webview 를 아래 버튼을 만들기 위해 button 을 이용합니다.



1. 프로젝트 생성
 HelloWebView



2. Main.xml 코딩

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
 
 <LinearLayout
 android:orientation="vertical"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:layout_weight="1">
 
  <WebView
  android:id="@+id/webview"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"/>
 
 </LinearLayout>
 
 <LinearLayout
 android:orientation="horizontal"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:layout_weight="8">
 
  <Button
  android:id="@+id/Button01"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="Home"
  android:layout_weight="1"
  android:textSize="8pt"/>
 
   <Button
   android:id="@+id/Button02"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="Portal"
  android:layout_weight="1"
  android:textSize="8pt"/>
 
   <Button
   android:id="@+id/Button03"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:text="Close"
  android:layout_weight="1"
  android:textSize="8pt"/>
 
 </LinearLayout>
 
</LinearLayout>

위 처럼 코딩 하시면 화면 구성은 끝납니다. 화면에 구성에 필요한 부분은 별도로 공부 하시면 도움이 많이 될겁니다. 별도로 포스트 할 예정입니다.



3. HellowWebView.java 코딩

package com.sample.HelloWebView;

import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;

public class HelloWebView extends Activity {
 private static final String URL1="http://m.daum.net/mini";
 private static final String URL2="http://m.naver.com";
 WebView webview;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        webview = (WebView) findViewById(R.id.webview);
        webview.getSettings().setJavaScriptEnabled(true);
        webview.loadUrl(URL1);

       
        webview.setWebViewClient(new HelloWebViewClient());
       
        Button b1 = (Button)findViewById(R.id.Button01);
        Button b2 = (Button)findViewById(R.id.Button02);
        Button b3 = (Button)findViewById(R.id.Button03);
       
        b1.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
          webview = (WebView) findViewById(R.id.webview);
          webview.getSettings().setJavaScriptEnabled(true);
          webview.loadUrl(URL1);
          webview.setWebViewClient(new HelloWebViewClient());
   }
  });
       
        b2.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
          webview = (WebView) findViewById(R.id.webview);
          webview.getSettings().setJavaScriptEnabled(true);
          webview.loadUrl(URL2);
          webview.setWebViewClient(new HelloWebViewClient());
   }
  });
       
       
        b3.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    finish();
   }
  });
    }
       
   
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
            webview.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
   
    private class HelloWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }
    }
}

다소 복잡해 보이지만 자동 완성 기능이 있으므로 어렵지 않습니다. 안드로이드는 자바와 XML로 구성되어 있다고 보면 됩니다. 특히 자바의 기초적인 부분을 잘 이해 하고 계시다면 개발은 어렵지 않을 거란 생각이 드네요.



4. 애플리케이션 훝어보기
 

 

Portal 버튼을 눌러 네이버로 이동한 화면입니다. 다시 Home 버튼을 누르면 다음으로 이동합니다. Close 는 화면을 종료하며 finish() 함수를 호출하여 간단하게 애플리케이션을 종료 할 수 있습니다.

안드로이드 JNI 에 대하여...


JNI JAVA에서 Native code를 사용할 수 있는 인터페이스이다. 좀 더 쉽게 말하면 CC++로 작성한 API JAVA에서 호출하게 해준다.

 

이를 위해서 framework의 안드로이드 소스 코드 중 service를 보자. (다른 쪽도 이와 유사하게 구현되어 있다.)

 

/framework/base/service/jni

/framework/base/service/java/com/android/server

 

jni 디렉토리의 Android.mk를 보면 libandroid_servers.so를 만들게 된다. 이는 java/com/android/server/SystemServer.java에서 다음과 같이 호출하게 된다.

 

 

    public static void main(String[] args) {

        if (SamplingProfilerIntegration.isEnabled()) {

            SamplingProfilerIntegration.start();

            timer = new Timer();

            timer.schedule(new TimerTask() {

                @Override

                public void run() {

                    SamplingProfilerIntegration.writeSnapshot("system_server");

                }

            }, SNAPSHOT_INTERVAL, SNAPSHOT_INTERVAL);

        }

 

        // The system server has to run all of the time, so it needs to be

        // as efficient as possible with its memory usage.

        VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);

 

        System.loadLibrary("android_servers");

        init1(args);

    }

 

System.loadLibrary에 의해서 libandroid_servers.so가 로드되며 최초로 호출되는 것이 JNI_OnLoad() 이 다. JNI_OnLoad() onload.cpp에서 정의되어 있으며, JNI_OnLoad()가 호출되기 전에 JNI로 정의한 메소드가 호출되어서는 안된다. 이유는 JNI_OnLoad()에서 각각의 서비스가 사용할 수 있는 native code를 등록하기 때문이다. 등록 전에 호출되면 JAVA VM은 관련 함수를 찾을 수 없게 된다. (JNI_OnLoad() System.loadLibrary에 의하여 자동으로 호출되기 때문에 java 파일에서는 호출되는 곳을 찾을 수 없다)

 

 

extern "C" jint JNI_OnLoad(JavaVM* vm, void* reserved)

{

    JNIEnv* env = NULL;

    jint result = -1;

 

    if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {

        LOGE("GetEnv failed!");

        return result;

    }

    LOG_ASSERT(env, "Could not retrieve the env!");

 

    register_android_server_KeyInputQueue(env);

    register_android_server_HardwareService(env);

    register_android_server_AlarmManagerService(env);

    register_android_server_BatteryService(env);

    register_android_server_SensorService(env);

    register_android_server_FallbackCheckinService(env);

    register_android_server_SystemServer(env);

 

    return JNI_VERSION_1_4;

}

 

여기에서 호출한 register 함수를 살펴볼 필요가 있다. Register_android_server_HardwareService()를 본다. jniRegisterNativeMethod()에 의해서 method_table com/android/server/HardwareService에 등록한다는 의미이다. 실제로 com/android/server/를 보면 HardwareService.java 파일이 있다. 위의 의미가 HardwareService.java 파일에 등록한다는 의미는 아니다. HardwareService.java 파일에서 정의한 HardwareService 클래스에 등록하여 사용한다는 의미이다. 이렇게 등록되면 HardwareService 클래스에 서는 method_table에 등록된 native 함수를 호출하여 사용할 수 있다. 당연히 다른 클래스에서는 native 함수를 호출할 수 없다.

 

 

static JNINativeMethod method_table[] = {

    { "init_native", "()I", (void*)init_native },

    { "finalize_native", "(I)V", (void*)finalize_native },

    { "setLight_native", "(IIIIIII)V", (void*)setLight_native },

    { "vibratorOn", "(J)V", (void*)vibratorOn },

    { "vibratorOff", "()V", (void*)vibratorOff }

};

 

int register_android_server_HardwareService(JNIEnv *env)

{

    return jniRegisterNativeMethods(env, "com/android/server/HardwareService",

            method_table, NELEM(method_table));

}

 

한 예로 SystemServer.cpp를 보면 SystemServer, ServerThread, DemoThread가 있다. com_android_server_SystemService.cpp 에서 정의된 gMethods[]에 새로운 native 코드 set_mtd_data를 추가하고 이를 ServerThread에서 호출하려고 하면 컴파일에서는 에러가 나지 않지만 실행 시에 에러가 난다. 이 를 해결하기 위해서는 다음과 같이 호출하여야 한다.

 

SystemServer.set_mtd_data(outputsel, (int)0);

 

 

SystemServer 클래스의 메소드 형태로만 호출이 가능하다.

 

만약 동일한 native 코드를 두개 이상의 독립된 클래스에서 사용하려면 당연한 얘기지만 각각에 대하여 따로 등록해야만 한다.

 

다시 com_android_server_HardwareService.cpp 파일의 method_table[]을 보자. 여기에서는 5개의 native 함수가 등록되어 있다. 첫번째 인자가 실제 java에서 호출되면 함수면이고, 두번째 인자는 입출력 인스턴스의 타입을 정의한다. 세번째 인자는 com_android_server_HardwareService.cpp에서 정의한 JNI 인터페 이스 함수이다.

 

HardwareService.java HardwareService 클래스에서 이를 이용하기 위해서는 native 메소드임을 선언하는 과정이 필요하다.

 

public class HardwareService extends IHardwareService.Stub {

    ……

 

private static native int init_native();

    private static native void finalize_native(int ptr);

 

    private static native void setLight_native(int ptr, int light, int color, int mode,

            int onMS, int offMS, int brightnessMode);

 

    private final Context mContext;

    private final PowerManager.WakeLock mWakeLock;

 

    private final IBatteryStats mBatteryStats;

 

    volatile VibrateThread mThread;

 

    private int mNativePointer;

 

native static void vibratorOn(long milliseconds);

    native static void vibratorOff();

}

 

JNI에서 새로운 native 함 수를 추가했다면 java 코드의 클래스에도 반드시 메소드 정의를 추가한다.

안드로이드 애플리케이션 Life Cycle


♦ 안드로이드 애플리케이션 Life Cycle
대부분의 경우에 안드로이드 애플리케이션은 자신 고유의 리눅스 프로세스에 의해 실행된다. 이 프로세스는 애플리케이션이 특정 코드를 수행할 필요가 있을 때 생성되고, 시스템이 다른 애플리케이션에 사용할 메모리를 요청 또는 더 이상 필요없어질 때까지 실행 상태를 유지한다.
안드로이드의 중요한 특성은 애플리케이션의 프로세스 Life Cycle은 애플리케이션 자신에 의해 직접 컨트롤되지 않는다는 것이다. 그것은 시스템이 실행상태를 알고 있는 애플리케이션 부분들의 조합(얼마나 사용자에게 중요한 것인가, 시스템의 여유 메모리가 얼마나 더 남아있는가)으로 결정된다.
애플리케이션 개발자들이 알아야 할 중요한 사항은 어떻게 서로 다른 애플리케이션 컴포넌트(Activity, Service, IntentReceiver)들이 애플리케이션의 프로세스에 영향을 미치는가 하는 것이다. 이러한 컴포넌트들을 정확하게 사용하지 않을 경우, 시스템은 중요한 일을 하고 있는 애플리케이션의 프로세스를 종료시킬 수 있다.
프로세스 lifecycle 버그의 일반적인 예는 onReceiveIntent() 메소드 내에서 Intent를 받고 함수에서 리턴될 때, IntentReceiver가 스레드를 시작하는 것이다. 한번 리턴되고 나면 시스템은 IntentReceiver를 비활성 상태로 인식하게 되고, 그것을 실행하는 호스팅 프로세스는 다른 애플리케이션 컴포넌트가 그 안에서 활성화 되어 있지 않는 한 필요없어지는 것이다. 그러므로 메모리 요청에 의해 언제든지 프로세스가 종료될 수 있고, 생성되어 실행되던 스레드도 종료된다. 이 문제의 해결법은 IntentReceiver로부터 Service를 실행하는 것이다. 그래서 시스템이 그 프로세스를 종료하기전에 여전히 어떤 작업이 활성화 되어 있음을 인식하게 하는 것이다.
유휴 메모리가 부족할 때 어떤 프로세스가 종료되어야 하는지 결정하는 것은 중요한 것이다. 안드로이드는 이것을 “importance hierarchy”를 베이스로 하고, “Importance hierarchy”내에서 실행중인 컴토넌트와 그 컴포넌트들의 상태에 따라 결정한다. 중요도의 순서는 다음과 같다.

 

(1) foreground process : 사용자가 조작중인 최상위 화면의 Activity(onResume() 메소드가 호출된 경우) 또는 현재 실행중인 IntentReceiver(onReceiveIntent() 메소드가 실행중)를 잡고 있는 프로세스이다. 시스템에는 아주 적은 수의 이런 프로세스가 있고, 이러한 프로세스가 실행되기에 극히 부족한 메모리가 있을 경우에만 종료된다. 이러한 동작은 일반적으로 기기가 메모리 페이징 상태에 다다랐을 때이며, 사용자 인터페이스 응답을 유지하기 위해서 취해진다.


(2) visible process : 사용자 화면에는 보여지지만 foreground는 아닌(onPause() 메소드를 호출한 경우) Activity를 잡고 있는 프로세스이다. 예를 들면 foreground activity가 다이알로그를 보여주며 이전 activity는 그 아래에 위치하는 것과 같다. 이런 프로세스는 매우 중요하며, 모든 foreground 프로세스 실행이 종료되기 전까지는 종료되지 않는다.


(3) service process : startService()를 호출한 Service를 잡고 있는 프로세스이다. 이러한 프로세스는 사용자에게 직접적으로 보여지는 것은 아니지만 사용자와 관련된 일반적인 일(mp3를 배경음으로 연주한다던가, 네트워크 데이터를 업로드/다운로드 한다던가 하는등)들을 한다. 그래서 이러한 프로세스는 모든 foreground, visible 프로세스를 유지하기에 메모리가 충분하지 않을때까지 계속 유지된다.


(4) background process : 사용자에게 현재는 보여지지 않는 activity(onStop() 메소드를 호출한 경우)를 잡고 있는 프로세스이다. 이런 프로세스들은 사용자에게 어떠한 영향을 주지 않으며, activity lifecycle을 정확하게 구현하기 위해서 제공된다. 시스템은 메모리가 부족할 경우 언제든지 이런 프로세스 수행을 멈출 수 있다. 가끔식 이러한 프로세스들이 많이 수행되고 있을 때, 메모리 부족시 가장 최근에 사용자에게 보여진 것이 가장 마지막으로 종료되도록 LRU 목록에 유지된다.


(5) empty process : 어떠한 활성화된 애플리케이션 컴포넌트들도 잡고있지 않는 프로세스이다. 이러한 프로세스를 유지하고 있는 이유는 다음에 컴포넌트의 애플리케이션이 시작되어야 할 때 시작 시간을 개선하기 위한 캐시로 사용하기 위해서다. 시스템은 캐쉬된 빈 프로세스와 커널 캐쉬 사이의 시스템 전체 리소스의 균형을 맞추기 위해 이런 프로세스를 종료시킨다.

Activity Manager

ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);

Alarm Manager

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);


Audio Manager 

AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

Clipboard Manager 

ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);

Connectivity Manager

ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

Input Method Manager

InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);


Keyguard Manager

KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);


Layout Inflater Manager 

LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);


Location Manager 

LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);


Notification Manager 

NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);


Power Manager 

PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);


Search Manage

SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);


Sensor Manager 

SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);


Telephony Manager 

TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);


Vibrator

Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);


Wallpaper Service 

WallpaperService wallpaperService = (WallpaperService) getSystemService(Context.WALLPAPER_SERVICE);


Wi-Fi Manager 

WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);


Window Manager 

WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
-----------------------------------------------------
- ■ 관련 명령어 요약 (아래 상세 설명에서 나오는 명령어들)
-----------------------------------------------------

    adb shell cat /proc/meminfo
    adb shell procrank -p
    adb shell top -m 10 -s cpu
    adb shell dumpsys meminfo 242

-----------------------------------------------------
- ■ procrank and top
-----------------------------------------------------

    adb shell procrank -p
    adb shell top -m 10 -s cpu

    Usage: procrank [ -W ] [ -v | -r | -p | -u | -h ]
        -v  Sort by VSS.
        -r  Sort by RSS.
        -p  Sort by PSS.
        -u  Sort by USS.
            (Default sort order is PSS.)
        -R  Reverse sort order (default is descending).
        -w  Display statistics for working set only.
        -W  Reset working set of all processes.
        -h  Display this help screen.

    Usage: top [ -m max_procs ] [ -n iterations ] [ -d delay ] [ -s sort_column ] [ -t ] [ -h ]
        -m num  Maximum number of processes to display.
        -n num  Updates to show before exiting.
        -d num  Seconds to wait between updates.
        -s col  Column to sort by (cpu,vss,rss,thr).
        -t      Show threads instead of processes.
        -h      Display this help screen.

-----------------------------------------------------
- ■ 시스템 메모리 사용 현황
-----------------------------------------------------

    우선 전체 시스템의 메모리부터 파악하자.
    $> adb shell 로 접속한 후 /proc/meminfo 를 열어본다.

    adb pull /proc/meminfo /tmp 명령으로 꺼내서 봐도 되고.
    adb shell cat /proc/meminfo 명령으로 봐도 된다.

-----------------------------------------------------
- ■ VSS 와 RSS
-----------------------------------------------------

    이론적으로(?) 프로세스가 차지하는 정확한 메모리의 크기를 알 수는 없다고 한다.
    다만, 프로세스에 매핑되는 page 수를 해석하는 다양한 방법이 있는데, VSS, RSS, USS, PSS 등이 그것이다.

    VSS(Virtual Set Size)
        프로세스와 관련된 버추얼 메모리(virtual memory) 크기.
        메모리 맵이 1M이면 프로세스가 어떤 리소스도 사용하지 않아도 VSS는 1MB가 된다.
        의미있는 수치라고 볼 수 없음.
    RSS(Resident Set Size)
        프로세스와 관련된 물리적 페이지(physical pages) 수.
        여러 프로세스 사이에서 공유된 페이지(shared pages) 수를 확인할 수 없어 별 의미없음.
        A프로세스의 RSS가 2MB, B프로세스의 RSS가 2MB일 때 실제 물리 페이지 수는 4MB이거나 2MB일 수 있다.

    어쨌거나 프로세스별 VSS 와 RSS 값은 top 명령어로 구할 수 있다.

-----------------------------------------------------
- ■ USS 와 PSS
-----------------------------------------------------

    VSS나 RSS보다 조금 더 의미있는 수치는 USS와 PSS인데,
    procrank 명령어로 구할 수 있다.

    USS(Unique Set Size)
        프로세스만의 고유한 페이지 수.
        공유되지 않는 프로세스에 private한 메모리 크기이다.
    PSS(Proportional Set Size)
        USS + (공유 페이지 / 공유하는 프로세스 수).
        즉, 프로세스 고유 메모리 사용량 + 하나의 프로세스가 차지하는 공유 메모리 비율이다.
        만약 A프로세스가 6MB 메모리를 사용하고 그 중 2MB가 그 프로세스의 고유 영역이라면,
        나머지 4MB는 공유 메모리이다. 4MB의 공유메모리를 4개의 프로세스가 공유하고 있다면
        PSS는 2MB + (4MB/4) = 3MB가 된다.

    PSS는 공유되는 페이지를 공유 프로세스의 수로 나누어서 좀 더 정확한 메모리 사용량을 파악할 수 있게 해준다.
    이게 프로세스가 사용하는 실제 메모리 크기에 가장 근접한 값이라고 볼 수 있다.

    프로세스별 PSS 수치는 "DDMS 의 Sysinfo 탭" 을 통해서도 볼 수 있다.
    파이그래프로 비주얼하게 보여주므로, 메모리 사용 비율을 쉽게 파악할 수 있다.

-----------------------------------------------------
- ■ 조금 더 상세한 메모리 정보
-----------------------------------------------------

    top과 procrank를 통해 애플리케이션의 개략적인 메모리 사용량을 알수 있었다면,
    dumpsys meminfo <PID(프로세스 ID)> 명령어로 약간 더 상세한 메모리 사용 정보를 구할 수 있다.
    dumpsys meminfo 명령어는 프로세스가 사용하는 native(C/C++)와 dalvik(JAVA) 영역을
    구분하여 보여주므로 달빅 VM 만의 메모리 크기를 알 수 있다.

    - Pss 필드 : procrank에 나온 PSS 값과 동일
    - shared dirty : 다른 프로세스와 공유하는 dirty pages(디스크로부터 페이징 불가능?)
    - private dirty : 프로세스 고유의 dirty pages

    Objects와 SQL 섹션에는 View/Context/Activity 등의 개수와 SQL 페이지 크기 등
    중요한 정보를 제공하므로 활용가치가 높다.

    dumpsys meminfo PID 명령

        dumpsys meminfo 출력 결과에 나온 dalvik 컬럼의
        size, allocated, free 필드값은 DDMS의 VM Heap 탭을 통해서도 확인할 수 있다.
        각각 VM Heap 탭의 Heap Size, Allocated, Free 컬럼에 해당한다.
        DDMS의 VM Heap 탭의 정보는 달빅 VM만의 메모리 정보일 뿐, 애플리케이션의 native 라이브러리가
        사용하는 메모리 정보는 제외되었다.




= 참고 원문 =
http://ecogeo.tistory.com/255
http://kohlerm.blogspot.com/2009/04/analyzing-memory-usage-off-your-android.html

'Linux 일반' 카테고리의 다른 글

우분투 64bit에서 안드로이드 개발에 적합한 이클립스 버전  (0) 2011.02.09
kscope 사용하기 - 1  (0) 2011.01.26
vi 명령어  (0) 2011.01.12
Makefile 문법법  (0) 2011.01.12
ext3 mount man page  (0) 2011.01.12

Near Field Communication

 

첨부파일 : 2008년도 NFC폰 시장 전망 및 업체 동향 - 정보통신정책

 

차기 아이폰과 안드로이드에서 지원하기로 한 NFC 기술에 대한 간략한 자료입니다.

 

http://en.wikipedia.org/wiki/Near_Field_Communication

http://wifisland.blog.me/10096977733?Redirect=Log

 

블루투스와 비교설명을 하였으나, 기존 900Mhz 대역 RFID 및 지그비 등의 장점등을 포함하고 있습니다.

현재의 결재, 교통, 주문, 배송, 입출입 등에서 사용되는 근거리 통신기술과 

바코드 기술 등을 모두 커버 할 수 도 있을 것 같습니다.

 

  • Supported data rates : 106,212,424 or 848 kbits/s

Baud

Active device

Passive device

424kBd Manchester, 10% ASK Manchester, 10% ASK
212kBd Manchester, 10% ASK Manchester, 10% ASK
106kBd Modified Miller, 100% ASK Manchester, 10% ASK

  • NFC vs. Bluetooth

NFC Bluetooth V2.1 Bluetooth V4.0
RFID compatible ISO 18000-3 active active
Standardisation body ISO/IEC Bluetooth SIG Bluetooth SIG
Network Standard ISO 13157 etc. IEEE 802.15.1 IEEE 802.15.1
Network Type Point-to-point WPAN WPAN
Cryptography not with RFID available available
Range < 0.2 m ~10 m (class 2) ~1 m (class 3)
Frequency 13.56 MHz 2.4-2.5 GHz 2.4-2.5 GHz
Bit rate 424 kbit/s 2.1 Mbit/s ~200 kbit/s
Set-up time < 0.1 s < 6 s < 1 s
Power consumption < 15mA (read) varies with class < 15 mA (xmit)


 

 

 

출처 : http://techblog.textcube.com/141 

 

NFC는 초단거리 무선통신 기술로 대략 10cm이내의 기기간에 통신을 가능하게 해 준다.

NFC는 ISO/IEC 14443 proximity-card standard (비접촉 카드 또는 RFID) 표준을 확장 한 것으로 스마트카드와 리더기를

하나로 합쳐놓은 것이라고 생각하면 된다.


ISO/IEEE 14443 표준을 확장한 것이기 때문에 NFC 디바이스간 뿐 아니고

기존의 ISO/IEEE 14443 리더기나 스마트카드와도 통신을 할 수 있다.

NFC는 기본적으로 휴대폰에서 사용할 목적으로 만들어졌다.

XD6BLFEoHX.jpg



간단한 기술적인 스펙으로는

- 13.56MHz의 ISM밴드에서 14KHz의 대역폭을 사용
- 최대 동작 거리: 20cm
- 지원하는 통신 속도: 106, 212, 424, 848 Kbit/s
- 동작모드: Passive, Active

NFC 포럼은 현재까지 11개의 스펙을 공개하고 있다.


   * NFC Data Exchange Format (NDEF) - Common data format for devices and tags
   * NFC Tag Types 1,2,3 &4 Operation - Defines RW operation for NFC tags
   * NFC Record Type Definition (RTD) - Standard record types used in messages between devices/tags 
   * Smart Poster RTD - For posters with tags with text, audio or other data
   * Text RTD - For records containing plain text
   * Uniform Resource Identifier (URI) RTD - For records that refer to an Internet resource
   * Generic COntrol Record Type Definition (RTD) - Ways to request an action
   * Connection Handover Specification - How to establish a connection with other wireless technologies

스펙은 http://www.nfc-forum.org/specs 에서 무료 다운받을 수 있다.


현재 NFC는 주로 휴대폰에서 사용되는데 3가지 방식으로 동작하고 있다.

- 카드 에뮬레이션: NFC디바이스(휴대폰)이 기존의 RFID카드와 같이 동작한다.

  즉 리더기에 기존의 카드 대신 휴대폰을 가져다 대면 된다.
- 리더 모드: NFC디바이스가 카드 리더기로 동작하는 모드이다.
- P2P 모드: 두대의 NFC디바이스가 서로 통신하는 모드이다.

이렇게 3가지 모드를 지원하기 때문에 NFC디바이스는 매우 다양한 방법으로 사용할 수 있다.

휴대폰이 교통카드, 문 열쇠등으로 동작(카드 에뮬레이션), 미술관, 박물관 등에서 작품에 휴대폰을 가까이 가져가면

해당 작품의 소개로 연결하기, 스마트카드 결제 단말기(리더모드), 휴대폰간 명함 교환 (P2P 모드)등등이 가능해진다.

그리고 통신거리가 매우 짧기 때문에 보안 문제도 간단해지고 통신을 위한 초기 셋업타임이 매우 짧은것이

 (0.1초 이하) 최대의 장점이다.

현재 휴대폰에는 노키아, 삼성, 모토롤라의 일부 소수 기중에서만 채용되어 있지만 여러곳에서

트라이얼 하는 곳이 많아서 조만간 급속하게 사용이 늘어나리라고 본다.

그리고 이 방식의 통신이 가장 널리 사용되고 있는 곳은 역시 일본이다. 일본은 소니가 개발한 FeLiCa를

교통카드에서부터 신용카드와 멤버쉽카드와 핸드폰, 결제 기능이 있는 손목시계 등, 다양한 곳에서 이 용하고 있다.

XP2Ka2Q48L.jpg


 

XFec5cnw4T.jpg


 

XL9stSU72g.jpg


 

XOacTG2tMp.gif



물론 현재 일본의 FeLiCa기능을 가지고 있는 휴대폰의 경우 카드 에뮬레이션 모드로만 동작한다.

(즉 스마트카드를 휴대폰에 집어넣은 형태) 소니의 발표에 의하면 2억개 이상의 FeLiCa칩을 판매하였다고 하고

가정용 USB리더기도 구매할 수 있다. 또한 일본 내수용 바이오 모델을 가지고 있는 사람들은

터치패드 오른쪽에 아래 사진과 같은 마크가 찍혀 있는것 봤을텐데 그 부분에 FeLiCa리더가 들어있다.

XPqF1LEu1N.jpg


libnfc 에서 오픈소스 NFC 라이브러리(리눅스, Mac OS X, 윈도우)를 구할 수 있고 몇일전에 NFC 칩을 판매하는

프랑스 회사인 Inside ContactlessLinux 2.6 and Windows CE 6.0용 프로토콜 스택인 Open NFC 3.4를

open source Apache License 2.0으로 공개했고 3월 말에는 안드로이드도 지원하는 Open NFC 3.5를 공개할 예정이다.

libnfc에는 여러가지 예제 코드와 함께 사용할 수 있는 하드웨어 목록을 확인할 수 있다.

XDXolTVonC.jpg


 

XNz91QTnsO.jpg



몇가지 종류의 하드웨어가 있는데 현재 가장 쉽고 저렴하게 구할 수 있는 리더로는 ACR-122 NFC가 있다.

몇곳에서 다른 이름으로 팔고 있지만 하드웨어는 기본적으로 동일하고 PN532 NFC Controller를 사용하고 있다.

XfMZC6x4jt.jpg


touchatag 에서도 ACR-122 리더기를 사용(윈도우, 맥용 드라이버 제공)한다.

다른곳에 비해 이 것이 가장 구하기 쉽고 저렴하다.

사진의 리더기와 10장의 스티커로 된 태그를 포함해서 $39.95, 추가로 태그만 구입하는 경우 25장에 $24.95, 500장에 $474.95이다.

touchatag에서도 라이브러리를 제공해 주지만 그걸 사용하지 않고 libnfc를 사용해도 된다.

집의 현관 문 앞에 저 USB리더기를 설치하고 스티커로 되어 있는 태그를 자신의 휴대폰 뒷면에 붙여주면

휴대폰을 집 열쇠로 사용할 수도 있다.

vi 명령어

 

1. 이동

h : 왼쪽

j : 아래

k : 위

l : 오른쪽

 

^n : 다음줄 이동

 

w : 단어이동
b : 단어의 맨 뒤로 이동
e : 단어의 끝으로 이동

$ : 라인 오른쪽 끝 이동
^ : 라인 왼쪽 끝 이동

H : 화면 위 이동
M : 화면 중간 이동
L : 화면 아래 이동

Ctrl + f  : 문서의 아래로 실제 이동( 다음페이지 )
Ctrl + b : 문서의 위로 실제 이동( 이전페이지 )

G : 특정 라인 이동


2. 편집
a : 추가
i : 삽입
o : 아랫줄

O : 윗줄

 

3. 삭제
x : 한 글자 삭제
dw :  현재 위치부터 한 단어 삭제
dd : 한 줄 삭제
D : 커서 오른쪽 전부 삭제

 

4. 수정
r : 한글자 수정
cw : 한단어 수정
cc : 한라인 수정
C : 커서 오른쪽 전부 수정
J : 문장합치기
~ : 대소문자 변경
u : 취소
U : 한라인에서 한 것 모두 취소

 

5. 저장
:w
:w filename
:q
:qw! <- read only 파일인 경우 강제로 저장

 

6. 복사
yw : 단어 복사
yy : 라인 복사
명령 프롬프트 1,20 co 30 : 1~20 의 범위를 잡아 복사한다.
명령 프롬프트 1,20 m 30 : 1~20 의 범위를 잡아 이동한다.
p : 붙여넣기


7. 설정 명령어
:set nu (넘버)
:set nonu (넘버해제)
:set ai(auto indent )
:set list ( 끝에 $ 표기)

 

8. 검색 명령어
/ : → ↓
? : ← ↑

/title : title 찾음,  n : 다음 title 을 찾음 , shift + n : 이전 title 을 찾음
?title : 역순검색
:%s/title/TITLE/g  전체문서(%) 에서 모든 title을 TITLE로 switch
:6,7s/7/5              6~7 번째 라인에서 7을 검색하여 5로 바꾼다.(단 한개만을 변경, g가 있어야 모두 변환)

'Linux 일반' 카테고리의 다른 글

kscope 사용하기 - 1  (0) 2011.01.26
android 프로세스별 메모리 사용량 보기  (0) 2011.01.13
Makefile 문법법  (0) 2011.01.12
ext3 mount man page  (0) 2011.01.12
diff/patch 사용하기  (0) 2011.01.12

이 부록은 GNU make 가 이해하는 지시어, 텍스트 조작 함수, 그리고 특수 변수들에 대해서 요약한 것이다. 다른 요약들을 보고자 한다면 See section 특수 내장 타겟 이름(Special Built-in Target Names), section 묵시적 규칙들의 카달로그(Catalogue of Implicit Rules), and section 옵션들의 요약(Summary of Options).

다음은 GNU make 가 인식하는 지시어들을 요약한 것이다:

define variable

endef
멀티-라인, 재귀적으로 확장되는 변수 하나를 정의한다. 
See section 명령들을 묶어서 정의하기(Defining Canned Command Sequences).
ifdef variable

ifndef variable

ifeq (a,b)

ifeq "a" "b"

ifeq 'a' 'b'

ifneq (a,b)

ifneq "a" "b"

ifneq 'a' 'b'

else

endif
makefile 의 조건 평가 부분. 
See section Makefile의 조건 부분(Conditional Parts of Makefiles).
include file
다른 makefile 을 포함한다. 
See section 다른 makefile 삽입(Including Other Makefiles).
override variable = value

override variable := value

override variable += value

override define variable

endef
변수 하나를 정의하고 이전의 정의를 오버라이드하다. 심지어 명령행에서의 정의까지 오버라이드한다.
See section override 지시어.
export
make 에게 차일드 프로세스들에게 디폴트로 모든 변수들을 익스포트하도록 지시.
See section 서브-make에 대한 통신 변수(Communicating Variables to a Sub-make).
export variable

export variable = value

export variable := value

export variable += value

unexport variable
make 에게 특정한 변수를 차일드 프로세스들에게 익스포트할 것인가 아닌가를 지시한다.
See section 서브-make에 대한 통신 변수(Communicating Variables to a Sub-make).
vpath pattern path
`%' 패턴과 일치하는 파일들에 대해서 검색 경로를 지정.
See section vpath 지시어.
vpath pattern
pattern 로 사전에 지정된 모든 검색 경로들을 제거.
vpath
vpath 지시어에 의해서 사전에 지정된 모든 검색 경로들을 제거.

다음은 텍스트 조작 함수들의 요약이다 (see section 텍스트 변환을 위한 함수(Functions for Transforming Text)): Here is a summary of the text manipulation functions (see section 텍스트 변환을 위한 함수(Functions for Transforming Text)):

$(subst from,to,text)
text 에서 from 를 to 로 교체.
See section 문자 대입과 분석을 위한 함수들(Functions for String Substitution and Analysis).
$(patsubst pattern,replacement,text)
text 에서 pattern 과 일치하는 것을 replacement 로 교체. 
See section 문자 대입과 분석을 위한 함수들(Functions for String Substitution and Analysis).
$(strip string)
string 로부터 여분의 공백 문자들을 제거.
See section 문자 대입과 분석을 위한 함수들(Functions for String Substitution and Analysis).
$(findstring find,text)
text 에서 find 를 찾음(locate).
See section 문자 대입과 분석을 위한 함수들(Functions for String Substitution and Analysis).
$(filter pattern...,text)
pattern 단어들중의 하나와 일치하는 text 내의 단어들을 선택. 
See section 문자 대입과 분석을 위한 함수들(Functions for String Substitution and Analysis).
$(filter-out pattern...,text)
pattern 단어들중의 하나와 일치하 지 않는 단어들을 text에서 선택.
See section 문자 대입과 분석을 위한 함수들(Functions for String Substitution and Analysis).
$(sort list)
list 에 있는 단어들을 사전식으로 소팅하고 중복된 것들을 제거.
See section 문자 대입과 분석을 위한 함수들(Functions for String Substitution and Analysis).
$(dir names...)
각 파일 이름에서 디렉토리 부분을 추출.
See section 파일 이름들을 위한 함수(Functions for File Names).
$(notdir names...)
각 파일 이름에서 비-디렉토리 부분을 추출.
See section 파일 이름들을 위한 함수(Functions for File Names).
$(suffix names...)
각 파일 이름의 확장자(마지막 `.'과 다음 문자들)를 추출.
See section 파일 이름들을 위한 함수(Functions for File Names).
$(basename names...)
각 파일 이름의 몸체 이름(확장자를 뺀 이름)을 추출.
See section 파일 이름들을 위한 함수(Functions for File Names).
$(addsuffix suffix,names...)
names 에 있는 각 단어의 뒤에다 suffix 를 붙인다. 
See section 파일 이름들을 위한 함수(Functions for File Names).
$(addprefix prefix,names...)
prefix 를 names 에 있는 각 단어 앞에다 붙인다. 
See section 파일 이름들을 위한 함수(Functions for File Names).
$(join list1,list2)
두 단어들의 병렬 리스트를 묶는다.
See section 파일 이름들을 위한 함수(Functions for File Names).
$(word n,text)
text 에서 n번째 단어(시작은 1)를 추출한다.
See section 파일 이름들을 위한 함수(Functions for File Names).
$(words text)
text 에서 단어들의 개수를 계산한다.
See section 파일 이름들을 위한 함수(Functions for File Names).
$(firstword names...)
names 의 첫번째 단어를 추출한다.
See section 파일 이름들을 위한 함수(Functions for File Names).
$(wildcard pattern...)
쉘 파일 이름 패턴 (`%' 패턴이 아님) 과 일치하는 파일 이름들을 찾는다. 
See section wildcard 함수(The Function wildcard).
$(shell command)
쉘 명령을 실행하고 그것의 결과를 리턴.
See section shell 함수(The shell Function).
$(origin variable)
make 변수 variable 가 정의된 방법을 설명하는 문자열을 리턴. 
See section origin 함수(The origin Function).
$(foreach var,words,text)
words 에 있는 각 단어를 가리키는 var 로 text 를 평가하고 그 결과를 서로 붙인다.
See section foreach 함수(The foreach Function).

다음은 완전한 정보를 대신할 자동 변수들See section 자동 변수들(Automatic Variables)의 요약이다.

$@
타겟의 파일 이름.
$%
타겟이 아카이브 멤버일 때, 타겟의 멤버 이름.
$<
첫번째 종속물의 이름.
$?
타겟보다 더 새로운 모든 종속물들의 이름. 이들 사이는 스페이스들로 구분된다. 아카이브 멤버들인 종속물들의 경우 이름있는 멤버들만이 사용된다 (see section 아카이브 파일을 갱신하기 위해서 make 사용하기(Using make to Update Archive Files)).
$^

$+
모든 종속물들의 이름. 이들 사이는 공백으로 구분된다. 아카이브 멤버들인 종속물들의 경우 이름있는 멤버만이 사용된다 (see section 아카이브 파일을 갱신하기 위해서 make 사용하기(Using make to Update Archive Files)). $^의 값은 중복된 종속물들을 생략한다. 반면에 $+는 그들을 그대로 가지고 그들의 순서를 유지한다.
$*
묵시적인 규칙이 매치된 줄기 (see section 패턴 비교 방법(How Patterns Match)).
$(@D)

$(@F)
$@의 디렉토리-안에 있는-파일 부분과 디렉토리 부분.
$(*D)

$(*F)
$*의 디렉토리-안에 있는-파일 부분과 디렉토리 부분.
$(%D)

$(%F)
$%의 디렉토리-안에 있는-파일 부분과 디렉토리 부분.
$(<D)

$(<F)
$<의 디렉토리-안에 있는-파일 부분과 디렉토리 부분.
$(^D)

$(^F)
$^의 디렉토리-안에 있는-파일 부분과 디렉토리 부분.
$(+D)

$(+F)
$+의 디렉토리-안에 있는-파일 부분과 디렉토리 부분.
$(?D)

$(?F)
$?의 디렉토리-안에 있는-파일 부분과 디렉토리 부분.

다음 변수들은 GNU make에 의해서 특별하게 사용된다:

MAKEFILES
make 의 모든 실행때마다 읽히는 makefile들. 
See section MAKEFILES 변수(The Variable MAKEFILES).
VPATH
현재 디렉토리에서 찾을 수 없는 파일들에 대한 디렉토리 검색 경로.
See section VPATH: 모든 종속물에 대한 검색 패스(Search Path for All Dependencies).
SHELL
시스템의 디폴트 명령 해석기의 이름. 일반적으로 `/bin/sh'. 명령들을 실행하는 데 사용되는 쉘을 변경하기 위해서 makefile 에서SHELL 을 설정할 수 있다. See section 명령 실행(Command Execution).
MAKESHELL
MS-DOS 에서만 사용되며 make 에 의해서 사용되는 명령 해석기의 이름. 이 값은 SHELL 의 값보다 우선한다. See section 명령 실행(Command Execution).
MAKE
make 가 호출된 이름. 이 변수를 명령에서 사용하는 것은 특수한 의미가 있다. See section MAKE 변수가 작동하는 방법(How the MAKE Variable Works).
MAKELEVEL
재귀적 진입의 단계 번호 (서브-make들의).
See section 서브-make에 대한 통신 변수(Communicating Variables to a Sub-make).
MAKEFLAGS
make 에 주어진 플래그들. 플래그들을 설정하기 위해서 환경에서나 makefile 안에서 이것을 설정할 수 있다.
See section 서브-make에 대한 통신 옵션(Communicating Options to a Sub-make).
MAKECMDGOALS
make 에 대해서 명령행에서 주어진 타겟. 이 변수를 설정하는 것은 make 의 작업에 어떤 영향도 미치지 않는다. 
See section goal을 지정하는 매개변수(Arguments to Specify the Goals).
CURDIR
현재 작업 디렉토리(모든 -C 옵션들이, 있다면 처리된 후)의 경로명으로 설정된다. 이 변수를 설정하는 것은 make 의 작업에 어떤 영향도 미치지 않는다.
See section make의 재귀적 사용(Recursive Use of make).
SUFFIXES
make 가 makefile 들을 읽기 전의 접미사들의 디폴트 리스트.

'Linux 일반' 카테고리의 다른 글

android 프로세스별 메모리 사용량 보기  (0) 2011.01.13
vi 명령어  (0) 2011.01.12
ext3 mount man page  (0) 2011.01.12
diff/patch 사용하기  (0) 2011.01.12
VirtualBox 설정 후 Windows 에서 USB 잡기  (0) 2011.01.12

mount(8) - Linux man page

Name

mount - mount a file system

Synopsis

mount [-lhV]

mount -a [-fFnrsvw] [-t vfstype] [-O optlist]
mount [-fnrsvw] [-o options [,...]] device | dir
mount [-fnrsvw] [-t vfstype] [-o options] device dir

Description

google_protectAndRun("render_ads.js::google_render_ad", google_handleError, google_render_ad);

All files accessible in a Unix system are arranged in one big tree, the file hierarchy, rooted at /. These files can be spread out over several devices. The mount command serves to attach the file system found on some device to the big file tree. Conversely, the umount(8) command will detach it again.

The standard form of the mount command, is


mount -t type device dir

This tells the kernel to attach the file system found on device (which is of type type) at the directory dir. The previous contents (if any) and owner and mode of dir become invisible, and as long as this file system remains mounted, the pathname dir refers to the root of the file system on device.

Three forms of invocation do not actually mount anything:


mount -h

prints a help message;


mount -V

prints a version string; and just

mount [-l] [-t type]

lists all mounted file systems (of type type). The option -l adds the (ext2, ext3 and XFS) labels in this listing. See below.

Since Linux 2.4.0 it is possible to remount part of the file hierarchy somewhere else. The call is


mount --bind olddir newdir

After this call the same contents is accessible in two places. One can also remount a single file (on a single file).

This call attaches only (part of) a single filesystem, not possible submounts. The entire file hierarchy including submounts is attached a second place using


mount --rbind olddir newdir

Note that the filesystem mount options will remain the same as those on the original mount point, and cannot be changed by passing the -o option along with --bind/--rbind.

Since Linux 2.5.1 it is possible to atomically move a mounted tree to another place. The call is


mount --move olddir newdir

Since Linux 2.6.15 it is possible to mark a mount and its submounts as shared, private, slave or unbindable. A shared mount provides ability to create mirrors of that mount such that mounts and umounts within any of the mirrors propagate to the other mirror. A slave mount receives propagation from its master, but any not vice-versa. A private mount carries no propagation abilities. A unbindable mount is a private mount which cannot cloned through a bind operation. Detailed semantics is documented in Documentation/sharedsubtree.txt file in the kernel source tree.


mount --make-shared mountpoint
mount --make-slave mountpoint
mount --make-private mountpoint
mount --make-unbindable mountpoint

The following commands allows one to recursively change the type of all the mounts under a given mountpoint.


mount --make-rshared mountpoint
mount --make-rslave mountpoint
mount --make-rprivate mountpoint
"mount --make-runbindable mountpoint"

The proc file system is not associated with a special device, and when mounting it, an arbitrary keyword, such as proc can be used instead of a device specification. (The customary choice none is less fortunate: the error message 'none busy' from umount can be confusing.)

Most devices are indicated by a file name (of a block special device), like /dev/sda1, but there are other possibilities. For example, in the case of an NFS mount, device may look like knuth.cwi.nl:/dir. It is possible to indicate a block special device using its volume label or UUID (see the -L and -U options below).

The file /etc/fstab (see fstab(5)), may contain lines describing what devices are usually mounted where, using which options. This file is used in three ways:

(i) The command


mount -a [-t type] [-O optlist]

(usually given in a bootscript) causes all file systems mentioned in fstab (of the proper type and/or having or not having the proper options) to be mounted as indicated, except for those whose line contains the noauto keyword. Adding the -F option will make mount fork, so that the filesystems are mounted simultaneously.

(ii) When mounting a file system mentioned in fstab, it suffices to give only the device, or only the mount point.

(iii) Normally, only the superuser can mount file systems. However, when fstab contains the user option on a line, anybody can mount the corresponding system.

Thus, given a line


/dev/cdrom /cd iso9660 ro,user,noauto,unhide

any user can mount the iso9660 file system found on his CDROM using the command


mount /dev/cdrom

or


mount /cd

For more details, see fstab(5). Only the user that mounted a filesystem can unmount it again. If any user should be able to unmount, then use users instead of user in the fstab line. The owner option is similar to the user option, with the restriction that the user must be the owner of the special file. This may be useful e.g. for /dev/fd if a login script makes the console user owner of this device. The group option is similar, with the restriction that the user must be member of the group of the special file.

The programs mount and umount maintain a list of currently mounted file systems in the file /etc/mtab. If no arguments are given to mount, this list is printed.

When the proc filesystem is mounted (say at /proc), the files /etc/mtab and /proc/mounts have very similar contents. The former has somewhat more information, such as the mount options used, but is not necessarily up-to-date (cf. the -n option below). It is possible to replace /etc/mtab by a symbolic link to /proc/mounts, and especially when you have very large numbers of mounts things will be much faster with that symlink, but some information is lost that way, and in particular working with the loop device will be less convenient, and using the "user" option will fail.

Options

The full set of options used by an invocation of mount is determined by first extracting the options for the file system from the fstab table, then applying any options specified by the -o argument, and finally applying a -r or -w option, when present.

Options available for the mount command:

-V
Output version.
-h
Print a help message.
-v
Verbose mode.
-a
Mount all filesystems (of the given types) mentioned in fstab.
-F
(Used in conjunction with -a.) Fork off a new incarnation of mount for each device. This will do the mounts on different devices or different NFS servers in parallel. This has the advantage that it is faster; also NFS timeouts go in parallel. A disadvantage is that the mounts are done in undefined order. Thus, you cannot use this option if you want to mount both /usr and /usr/spool.
-f
Causes everything to be done except for the actual system call; if it's not obvious, this ''fakes'' mounting the file system. This option is useful in conjunction with the -v flag to determine what the mount command is trying to do. It can also be used to add entries for devices that were mounted earlier with the -n option.
-i
Don't call the /sbin/mount.<filesystem> helper even if it exists.
-l
Add the ext2, ext3 and XFS labels in the mount output. Mount must have permission to read the disk device (e.g. be suid root) for this to work. One can set such a label for ext2 or ext3 using the e2label(8) utility, or for XFS using xfs_admin(8), or for reiserfs using reiserfstune(8).
-n
Mount without writing in /etc/mtab. This is necessary for example when /etc is on a read-only file system.
-pnum
In case of a loop mount with encryption, read the passphrase from file descriptor num instead of from the terminal.
-s
Tolerate sloppy mount options rather than failing. This will ignore mount options not supported by a filesystem type. Not all filesystems support this option. This option exists for support of the Linux autofs-based automounter.
-r
Mount the file system read-only. A synonym is -o ro.
-w
Mount the file system read/write. This is the default. A synonym is -o rw.
-L label
Mount the partition that has the specified label.
-U uuid
Mount the partition that has the specified uuid. These two options require the file /proc/partitions (present since Linux 2.1.116) to exist.
-t vfstype
The argument following the -t is used to indicate the file system type. The file system types which are currently supported include: adfs, affs, autofs, cifs, coda, coherent, cramfs, debugfs, devpts, efs, ext, ext2, ext3, hfs, hpfs, iso9660, jfs, minix, msdos, ncpfs, nfs, nfs4, ntfs, proc, qnx4, ramfs, reiserfs, romfs, smbfs, sysv, tmpfs, udf, ufs, umsdos, usbfs, vfat, xenix, xfs, xiafs. Note that coherent, sysv and xenix are equivalent and that xenix and coherent will be removed at some point in the future -- use sysv instead. Since kernel version 2.1.21 the types ext and xiafs do not exist anymore. Earlier, usbfs was known as usbdevfs.

For most types all the mount program has to do is issue a simple mount(2) system call, and no detailed knowledge of the filesystem type is required. For a few types however (like nfs, nfs4, cifs, smbfs, ncpfs) ad hoc code is necessary. The nfs ad hoc code is built in, but cifs, smbfs, and ncpfs have a separate mount program. In order to make it possible to treat all types in a uniform way, mount will execute the program /sbin/mount.TYPE (if that exists) when called with type TYPE. Since various versions of the smbmount program have different calling conventions, /sbin/mount.smbfs may have to be a shell script that sets up the desired call.

If no -t option is given, or if the auto type is specified, mount will try to guess the desired type. If mount was compiled with the blkid library, the guessing is done by this library. Otherwise, mount guesses itself by probing the superblock; if that does not turn up anything that looks familiar, mount will try to read the file /etc/filesystems, or, if that does not exist, /proc/filesystems. All of the filesystem types listed there will be tried, except for those that are labeled "nodev" (e.g., devpts, proc, nfs, and nfs4). If /etc/filesystems ends in a line with a single * only, mount will read /proc/filesystems afterwards.

The auto type may be useful for user-mounted floppies. Creating a file /etc/filesystems can be useful to change the probe order (e.g., to try vfat before msdos or ext3 before ext2) or if you use a kernel module autoloader. Warning: the probing uses a heuristic (the presence of appropriate 'magic'), and could recognize the wrong filesystem type, possibly with catastrophic consequences. If your data is valuable, don't ask mount to guess.

More than one type may be specified in a comma separated list. The list of file system types can be prefixed with no to specify the file system types on which no action should be taken. (This can be meaningful with the -a option.)

For example, the command:

mount -a -t nomsdos,ext mounts all file systems except those of type msdos and ext.

-O
Used in conjunction with -a, to limit the set of filesystems to which the -a is applied. Like -t in this regard except that it is useless except in the context of -a. For example, the command:

mount -a -O no_netdev mounts all file systems except those which have the option _netdev specified in the options field in the /etc/fstab file.

It is different from -t in that each option is matched exactly; a leading no at the beginning of one option does not negate the rest.

The -t and -O options are cumulative in effect; that is, the command

mount -a -t ext2 -O _netdev

mounts all ext2 filesystems with the _netdev option, not all filesystems that are either ext2 or have the _netdev option specified.

-o
Options are specified with a -o flag followed by a comma separated string of options. Some of these options are only useful when they appear in the /etc/fstab file. The following options apply to any file system that is being mounted (but not every file system actually honors them - e.g., the sync option today has effect only for ext2, ext3, fat, vfat and ufs):
async
All I/O to the file system should be done asynchronously.
atime
Update inode access time for each access. This is the default.
auto
Can be mounted with the -a option.
defaults
Use default options: rw, suid, dev, exec, auto, nouser, and async.
dev
Interpret character or block special devices on the file system.
exec
Permit execution of binaries.
group
Allow an ordinary (i.e., non-root) user to mount the file system if one of his groups matches the group of the device. This option implies the options nosuid and nodev (unless overridden by subsequent options, as in the option line group,dev,suid).
mand
Allow mandatory locks on this filesystem. See fcntl(2).
_netdev
The filesystem resides on a device that requires network access (used to prevent the system from attempting to mount these filesystems until the network has been enabled on the system).
noatime
Do not update inode access times on this file system (e.g, for faster access on the news spool to speed up news servers).
nodiratime
Do not update directory inode access times on this filesystem.
noauto
Can only be mounted explicitly (i.e., the -a option will not cause the file system to be mounted).
nodev
Do not interpret character or block special devices on the file system.
noexec
Do not allow direct execution of any binaries on the mounted file system. (Until recently it was possible to run binaries anyway using a command like /lib/ld*.so /mnt/binary. This trick fails since Linux 2.4.25 / 2.6.0.)
nomand
Do not allow mandatory locks on this filesystem.
nosuid
Do not allow set-user-identifier or set-group-identifier bits to take effect. (This seems safe, but is in fact rather unsafe if you have suidperl(1) installed.)
nouser
Forbid an ordinary (i.e., non-root) user to mount the file system. This is the default.
owner
Allow an ordinary (i.e., non-root) user to mount the file system if he is the owner of the device. This option implies the options nosuid and nodev (unless overridden by subsequent options, as in the option line owner,dev,suid).
remount
Attempt to remount an already-mounted file system. This is commonly used to change the mount flags for a file system, especially to make a readonly file system writeable. It does not change device or mount point.
ro
Mount the file system read-only.
rw
Mount the file system read-write.
suid
Allow set-user-identifier or set-group-identifier bits to take effect.
sync
All I/O to the file system should be done synchronously. In case of media with limited number of write cycles (e.g. some flash drives) "sync" may cause life-cycle shortening.
dirsync
All directory updates within the file system should be done synchronously. This affects the following system calls: creat, link, unlink, symlink, mkdir, rmdir, mknod and rename.
user
Allow an ordinary user to mount the file system. The name of the mounting user is written to mtab so that he can unmount the file system again. This option implies the options noexec, nosuid, and nodev (unless overridden by subsequent options, as in the option line user,exec,dev,suid).
users
Allow every user to mount and unmount the file system. This option implies the options noexec, nosuid, and nodev (unless overridden by subsequent options, as in the option line users,exec,dev,suid).
context=context, fscontext=context and defcontext=context
The context= option is useful when mounting filesystems that do not support extended attributes, such as a floppy or hard disk formatted with VFAT, or systems that are not normally running under SELinux, such as an ext3 formatted disk from a non-SELinux workstation. You can also use context= on filesystems you do not trust, such as a floppy. It also helps in compatibility with xattr-supporting filesystems on earlier 2.4.<x> kernel versions. Even where xattrs are supported, you can save time not having to label every file by assigning the entire disk one security context.

A commonly used option for removable media is context=system_u:object_r:removable_t.

Two other options are fscontext= and defcontext=, both of which are mutually exclusive of the context option. This means you can use fscontext and defcontext with each other, but neither can be used with context.

The fscontext= option works for all filesystems, regardless of their xattr support. The fscontext option sets the overarching filesystem label to a specific security context. This filesystem label is separate from the individual labels on the files. It represents the entire filesystem for certain kinds of permission checks, such as during mount or file creation. Individual file labels are still obtained from the xattrs on the files themselves. The context option actually sets the aggregate context that fscontext provides, in addition to supplying the same label for individual files.

You can set the default security context for unlabeled files using defcontext= option. This overrides the value set for unlabeled files in the policy and requires a file system that supports xattr labeling.

For more details see selinux(8)

--bind
Remount a subtree somewhere else (so that its contents are available in both places). See above.
--move
Move a subtree to some other place. See above.

Filesystem Specific Mount Options

The following options apply only to certain file systems. We sort them by file system. They all follow the -o flag.

What options are supported depends a bit on the running kernel. More info may be found in the kernel source subdirectory Documentation/filesystems.

Mount options for adfs

uid=value and gid=value
Set the owner and group of the files in the file system (default: uid=gid=0).
ownmask=value and othmask=value
Set the permission mask for ADFS 'owner' permissions and 'other' permissions, respectively (default: 0700 and 0077, respectively). See also /usr/src/linux/Documentation/filesystems/adfs.txt.

Mount options for affs

uid=value and gid=value
Set the owner and group of the root of the file system (default: uid=gid=0, but with option uid or gid without specified value, the uid and gid of the current process are taken).
setuid=value and setgid=value
Set the owner and group of all files.
mode=value
Set the mode of all files to value & 0777 disregarding the original permissions. Add search permission to directories that have read permission. The value is given in octal.
protect
Do not allow any changes to the protection bits on the file system.
usemp
Set uid and gid of the root of the file system to the uid and gid of the mount point upon the first sync or umount, and then clear this option. Strange...
verbose
Print an informational message for each successful mount.
prefix=string
Prefix used before volume name, when following a link.
volume=string
Prefix (of length at most 30) used before '/' when following a symbolic link.
reserved=value
(Default: 2.) Number of unused blocks at the start of the device.
root=value
Give explicitly the location of the root block.
bs=value
Give blocksize. Allowed values are 512, 1024, 2048, 4096.
grpquota / noquota / quota / usrquota
These options are accepted but ignored. (However, quota utilities may react to such strings in /etc/fstab.)

Mount options for cifs

See the options section of the mount.cifs(8) man page (cifs-mount package must be installed).

Mount options for cifs

Just like nfs or smbfs implementation expects a binary argument to the mount system call. This argument is constructed by mount.cifs(8) and the current version of mount (2.12) does not know anything about cifs.

Mount options for coherent

None.

Mount options for debugfs

The debugfs file system is a pseudo file system, traditionally mounted on /sys/kernel/debug. There are no mount options.

Mount options for devpts

The devpts file system is a pseudo file system, traditionally mounted on /dev/pts. In order to acquire a pseudo terminal, a process opens /dev/ptmx; the number of the pseudo terminal is then made available to the process and the pseudo terminal slave can be accessed as /dev/pts/<number>.

uid=value and gid=value
This sets the owner or the group of newly created PTYs to the specified values. When nothing is specified, they will be set to the UID and GID of the creating process. For example, if there is a tty group with GID 5, then gid=5 will cause newly created PTYs to belong to the tty group.
mode=value
Set the mode of newly created PTYs to the specified value. The default is 0600. A value of mode=620 and gid=5 makes "mesg y" the default on newly created PTYs.

Mount options for ext

None. Note that the 'ext' file system is obsolete. Don't use it. Since Linux version 2.1.21 extfs is no longer part of the kernel source.

Mount options for ext2

The 'ext2' file system is the standard Linux file system. Since Linux 2.5.46, for most mount options the default is determined by the filesystem superblock. Set them with tune2fs(8).

acl / noacl
Support POSIX Access Control Lists (or not).
bsddf / minixdf
Set the behaviour for the statfs system call. The minixdf behaviour is to return in the f_blocks field the total number of blocks of the file system, while the bsddf behaviour (which is the default) is to subtract the overhead blocks used by the ext2 file system and not available for file storage.

Thus

% mount /k -o minixdf; df /k; umount /k
Filesystem 1024-blocks Used Available Capacity Mounted on
/dev/sda6 2630655 86954 2412169 3% /k
% mount /k -o bsddf; df /k; umount /k
Filesystem 1024-blocks Used Available Capacity Mounted on
/dev/sda6 2543714 13 2412169 0% /k

(Note that this example shows that one can add command line options to the options given in /etc/fstab.)

check=none / nocheck
No checking is done at mount time. This is the default. This is fast. It is wise to invoke e2fsck(8) every now and then, e.g. at boot time.
debug
Print debugging info upon each (re)mount.
errors=continue / errors=remount-ro / errors=panic
Define the behaviour when an error is encountered. (Either ignore errors and just mark the file system erroneous and continue, or remount the file system read-only, or panic and halt the system.) The default is set in the filesystem superblock, and can be changed using tune2fs(8).
grpid or bsdgroups / nogrpid or sysvgroups
These options define what group id a newly created file gets. When grpid is set, it takes the group id of the directory in which it is created; otherwise (the default) it takes the fsgid of the current process, unless the directory has the setgid bit set, in which case it takes the gid from the parent directory, and also gets the setgid bit set if it is a directory itself.
grpquota / noquota / quota / usrquota
These options are accepted but ignored.
nobh
Do not attach buffer_heads to file pagecache. (Since 2.5.49.)
nouid32
Disables 32-bit UIDs and GIDs. This is for interoperability with older kernels which only store and expect 16-bit values.
oldalloc or orlov
Use old allocator or Orlov allocator for new inodes. Orlov is default.
resgid=n and resuid=n
The ext2 file system reserves a certain percentage of the available space (by default 5%, see mke2fs(8) and tune2fs(8)). These options determine who can use the reserved blocks. (Roughly: whoever has the specified uid, or belongs to the specified group.)
sb=n
Instead of block 1, use block n as superblock. This could be useful when the filesystem has been damaged. (Earlier, copies of the superblock would be made every 8192 blocks: in block 1, 8193, 16385, ... (and one got thousands of copies on a big filesystem). Since version 1.08, mke2fs has a -s (sparse superblock) option to reduce the number of backup superblocks, and since version 1.15 this is the default. Note that this may mean that ext2 filesystems created by a recent mke2fs cannot be mounted r/w under Linux 2.0.*.) The block number here uses 1k units. Thus, if you want to use logical block 32768 on a filesystem with 4k blocks, use "sb=131072".
user_xattr / nouser_xattr
Support "user." extended attributes (or not).

Mount options for ext3

The 'ext3' file system is a version of the ext2 file system which has been enhanced with journalling. It supports the same options as ext2 as well as the following additions:

journal=update
Update the ext3 file system's journal to the current format.
journal=inum
When a journal already exists, this option is ignored. Otherwise, it specifies the number of the inode which will represent the ext3 file system's journal file; ext3 will create a new journal, overwriting the old contents of the file whose inode number is inum.
noload
Do not load the ext3 file system's journal on mounting.
data=journal / data=ordered / data=writeback
Specifies the journalling mode for file data. Metadata is always journaled. To use modes other than ordered on the root file system, pass the mode to the kernel as boot parameter, e.g. rootflags=data=journal.
journal
All data is committed into the journal prior to being written into the main file system.
ordered
This is the default mode. All data is forced directly out to the main file system prior to its metadata being committed to the journal.
writeback
Data ordering is not preserved - data may be written into the main file system after its metadata has been committed to the journal. This is rumoured to be the highest-throughput option. It guarantees internal file system integrity, however it can allow old data to appear in files after a crash and journal recovery.
commit=nrsec
Sync all data and metadata every nrsec seconds. The default value is 5 seconds. Zero means default.

Mount options for fat

(Note: fat is not a separate filesystem, but a common part of the msdos, umsdos and vfat filesystems.)

blocksize=512 / blocksize=1024 / blocksize=2048
Set blocksize (default 512).
uid=value and gid=value
Set the owner and group of all files. (Default: the uid and gid of the current process.)
umask=value
Set the umask (the bitmask of the permissions that are not present). The default is the umask of the current process. The value is given in octal.
dmask=value
Set the umask applied to directories only. The default is the umask of the current process. The value is given in octal.
fmask=value
Set the umask applied to regular files only. The default is the umask of the current process. The value is given in octal.
check=value
Three different levels of pickyness can be chosen:
r[elaxed]
Upper and lower case are accepted and equivalent, long name parts are truncated (e.g. verylongname.foobar becomes verylong.foo), leading and embedded spaces are accepted in each name part (name and extension).
n[ormal]
Like "relaxed", but many special characters (*, ?, <, spaces, etc.) are rejected. This is the default.
s[trict]
Like "normal", but names may not contain long parts and special characters that are sometimes used on Linux, but are not accepted by MS-DOS are rejected. (+, =, spaces, etc.)
codepage=value
Sets the codepage for converting to shortname characters on FAT and VFAT filesystems. By default, codepage 437 is used.
conv=b[inary] / conv=t[ext] / conv=a[uto]
The fat file system can perform CRLF<-->NL (MS-DOS text format to UNIX text format) conversion in the kernel. The following conversion modes are available:
binary
no translation is performed. This is the default.
text
CRLF<-->NL translation is performed on all files.
auto
CRLF<-->NL translation is performed on all files that don't have a "well-known binary" extension. The list of known extensions can be found at the beginning of fs/fat/misc.c (as of 2.0, the list is: exe, com, bin, app, sys, drv, ovl, ovr, obj, lib, dll, pif, arc, zip, lha, lzh, zoo, tar, z, arj, tz, taz, tzp, tpz, gz, tgz, deb, gif, bmp, tif, gl, jpg, pcx, tfm, vf, gf, pk, pxl, dvi).

Programs that do computed lseeks won't like in-kernel text conversion. Several people have had their data ruined by this translation. Beware!

For file systems mounted in binary mode, a conversion tool (fromdos/todos) is available.

cvf_format=module
Forces the driver to use the CVF (Compressed Volume File) module cvf_module instead of auto-detection. If the kernel supports kmod, the cvf_format=xxx option also controls on-demand CVF module loading.
cvf_option=option
Option passed to the CVF module.
debug
Turn on the debug flag. A version string and a list of file system parameters will be printed (these data are also printed if the parameters appear to be inconsistent).
fat=12 / fat=16 / fat=32
Specify a 12, 16 or 32 bit fat. This overrides the automatic FAT type detection routine. Use with caution!
iocharset=value
Character set to use for converting between 8 bit characters and 16 bit Unicode characters. The default is iso8859-1. Long filenames are stored on disk in Unicode format.
quiet
Turn on the quiet flag. Attempts to chown or chmod files do not return errors, although they fail. Use with caution!
sys_immutable, showexec, dots, nodots, dotsOK=[yes|no]
Various misguided attempts to force Unix or DOS conventions onto a FAT file system.

Mount options for hfs

creator=cccc, type=cccc
Set the creator/type values as shown by the MacOS finder used for creating new files. Default values: '????'.
uid=n, gid=n
Set the owner and group of all files. (Default: the uid and gid of the current process.)
dir_umask=n, file_umask=n, umask=n
Set the umask used for all directories, all regular files, or all files and directories. Defaults to the umask of the current process.
session=n
Select the CDROM session to mount. Defaults to leaving that decision to the CDROM driver. This option will fail with anything but a CDROM as underlying device.
part=n
Select partition number n from the device. Only makes sense for CDROMS. Defaults to not parsing the partition table at all.
quiet
Don't complain about invalid mount options.

Mount options for hpfs

uid=value and gid=value
Set the owner and group of all files. (Default: the uid and gid of the current process.)
umask=value
Set the umask (the bitmask of the permissions that are not present). The default is the umask of the current process. The value is given in octal.
case=lower / case=asis
Convert all files names to lower case, or leave them. (Default: case=lower.)
conv=binary / conv=text / conv=auto
For conv=text, delete some random CRs (in particular, all followed by NL) when reading a file. For conv=auto, choose more or less at random between conv=binary and conv=text. For conv=binary, just read what is in the file. This is the default.
nocheck
Do not abort mounting when certain consistency checks fail.

Mount options for iso9660

ISO 9660 is a standard describing a filesystem structure to be used on CD-ROMs. (This filesystem type is also seen on some DVDs. See also the udf filesystem.)

Normal iso9660 filenames appear in a 8.3 format (i.e., DOS-like restrictions on filename length), and in addition all characters are in upper case. Also there is no field for file ownership, protection, number of links, provision for block/character devices, etc.

Rock Ridge is an extension to iso9660 that provides all of these unix like features. Basically there are extensions to each directory record that supply all of the additional information, and when Rock Ridge is in use, the filesystem is indistinguishable from a normal UNIX file system (except that it is read-only, of course).

norock
Disable the use of Rock Ridge extensions, even if available. Cf. map.
nojoliet
Disable the use of Microsoft Joliet extensions, even if available. Cf. map.
check=r[elaxed] / check=s[trict]
With check=relaxed, a filename is first converted to lower case before doing the lookup. This is probably only meaningful together with norock and map=normal. (Default: check=strict.)
uid=value and gid=value
Give all files in the file system the indicated user or group id, possibly overriding the information found in the Rock Ridge extensions. (Default: uid=0,gid=0.)
map=n[ormal] / map=o[ff] / map=a[corn]
For non-Rock Ridge volumes, normal name translation maps upper to lower case ASCII, drops a trailing ';1', and converts ';' to '.'. With map=off no name translation is done. See norock. (Default: map=normal.) map=acorn is like map=normal but also apply Acorn extensions if present.
mode=value
For non-Rock Ridge volumes, give all files the indicated mode. (Default: read permission for everybody.) Since Linux 2.1.37 one no longer needs to specify the mode in decimal. (Octal is indicated by a leading 0.)
unhide
Also show hidden and associated files. (If the ordinary files and the associated or hidden files have the same filenames, this may make the ordinary files inaccessible.)
block=[512|1024|2048]
Set the block size to the indicated value. (Default: block=1024.)
conv=a[uto] / conv=b[inary] / conv=m[text] / conv=t[ext]
(Default: conv=binary.) Since Linux 1.3.54 this option has no effect anymore. (And non-binary settings used to be very dangerous, possibly leading to silent data corruption.)
cruft
If the high byte of the file length contains other garbage, set this mount option to ignore the high order bits of the file length. This implies that a file cannot be larger than 16MB.
session=x
Select number of session on multisession CD. (Since 2.3.4.)
sbsector=xxx
Session begins from sector xxx. (Since 2.3.4.)

The following options are the same as for vfat and specifying them only makes sense when using discs encoded using Microsoft's Joliet extensions.

iocharset=value
Character set to use for converting 16 bit Unicode characters on CD to 8 bit characters. The default is iso8859-1.
utf8
Convert 16 bit Unicode characters on CD to UTF-8.

Mount options for jfs

iocharset=name
Character set to use for converting from Unicode to ASCII. The default is to do no conversion. Use iocharset=utf8 for UTF8 translations. This requires CONFIG_NLS_UTF8 to be set in the kernel .config file.
resize=value
Resize the volume to value blocks. JFS only supports growing a volume, not shrinking it. This option is only valid during a remount, when the volume is mounted read-write. The resize keyword with no value will grow the volume to the full size of the partition.
nointegrity
Do not write to the journal. The primary use of this option is to allow for higher performance when restoring a volume from backup media. The integrity of the volume is not guaranteed if the system abnormally abends.
integrity
Default. Commit metadata changes to the journal. Use this option to remount a volume where the nointegrity option was previously specified in order to restore normal behavior.
errors=continue / errors=remount-ro / errors=panic
Define the behaviour when an error is encountered. (Either ignore errors and just mark the file system erroneous and continue, or remount the file system read-only, or panic and halt the system.)
noquota / quota / usrquota / grpquota
These options are accepted but ignored.

Mount options for minix

None.

Mount options for msdos

See mount options for fat. If the msdos file system detects an inconsistency, it reports an error and sets the file system read-only. The file system can be made writeable again by remounting it.

Mount options for ncpfs

Just like nfs, the ncpfs implementation expects a binary argument (a struct ncp_mount_data) to the mount system call. This argument is constructed by ncpmount(8) and the current version of mount (2.12) does not know anything about ncpfs.

Mount options for nfs

Instead of a textual option string, parsed by the kernel, the nfs file system expects a binary argument of type struct nfs_mount_data. The program mount itself parses the following options of the form 'tag=value', and puts them in the structure mentioned: rsize=n, wsize=n, timeo=n, retrans=n, acregmin=n, acregmax=n, acdirmin=n, acdirmax=n, actimeo=n, retry=n, port=n, mountport=n, mounthost=name, mountprog=n, mountvers=n, nfsprog=n, nfsvers=n, namlen=n. The option addr=n is accepted but ignored. Also the following Boolean options, possibly preceded by no are recognized: bg, fg, soft, hard, intr, posix, cto, ac, tcp, udp, lock. For details, see nfs(5).

Especially useful options include

rsize=32768,wsize=32768
This causes the NFS client to try to negotiate a buffer size up to the size specified. A large buffer size does improve performance, but both the server and client have to support it. In the case where one of these does not support the size specified, the size negotiated will be the largest that both support.
intr
This will allow NFS operations (on hard mounts) to be interrupted while waiting for a response from the server.
nolock
Do not use locking. Do not start lockd.

Mount options for nfs4

Instead of a textual option string, parsed by the kernel, the nfs4 file system expects a binary argument of type struct nfs4_mount_data. The program mount itself parses the following options of the form 'tag=value', and puts them in the structure mentioned: rsize=n, wsize=n, timeo=n, retrans=n, acregmin=n, acregmax=n, acdirmin=n, acdirmax=n, actimeo=n, retry=n, port=n, proto=n, clientaddr=n, sec=n. The option addr=n is accepted but ignored. Also the following Boolean options, possibly preceded by no are recognized: bg, fg, soft, hard, intr, cto, ac, For details, see nfs(5).

Especially useful options include

rsize=32768,wsize=32768
This causes the NFS4 client to try to negotiate a buffer size up to the size specified. A large buffer size does improve performance, but both the server and client have to support it. In the case where one of these does not support the size specified, the size negotiated will be the largest that both support.
intr
This will allow NFS4 operations (on hard mounts) to be interrupted while waiting for a response from the server.

Mount options for ntfs

iocharset=name
Character set to use when returning file names. Unlike VFAT, NTFS suppresses names that contain unconvertible characters. Deprecated.
nls=name
New name for the option earlier called iocharset.
utf8
Use UTF-8 for converting file names.
uni_xlate=[0|1|2]
For 0 (or 'no' or 'false'), do not use escape sequences for unknown Unicode characters. For 1 (or 'yes' or 'true') or 2, use vfat-style 4-byte escape sequences starting with ":". Here 2 give a little-endian encoding and 1 a byteswapped bigendian encoding.
posix=[0|1]
If enabled (posix=1), the file system distinguishes between upper and lower case. The 8.3 alias names are presented as hard links instead of being suppressed.
uid=value, gid=value and umask=value
Set the file permission on the filesystem. The umask value is given in octal. By default, the files are owned by root and not readable by somebody else.

Mount options for proc

uid=value and gid=value
These options are recognized, but have no effect as far as I can see.

Mount options for ramfs

Ramfs is a memory based filesystem. Mount it and you have it. Unmount it and it is gone. Present since Linux 2.3.99pre4. There are no mount options.

Mount options for reiserfs

Reiserfs is a journaling filesystem. The reiserfs mount options are more fully described at http://www.namesys.com/mount-options.html.

conv
Instructs version 3.6 reiserfs software to mount a version 3.5 file system, using the 3.6 format for newly created objects. This file system will no longer be compatible with reiserfs 3.5 tools.
hash=rupasov / hash=tea / hash=r5 / hash=detect
Choose which hash function reiserfs will use to find files within directories.
rupasov
A hash invented by Yury Yu. Rupasov. It is fast and preserves locality, mapping lexicographically close file names to close hash values. This option should not be used, as it causes a high probability of hash collisions.
tea
A Davis-Meyer function implemented by Jeremy Fitzhardinge. It uses hash permuting bits in the name. It gets high randomness and, therefore, low probability of hash collisions at some CPU cost. This may be used if EHASHCOLLISION errors are experienced with the r5 hash.
r5
A modified version of the rupasov hash. It is used by default and is the best choice unless the file system has huge directories and unusual file-name patterns.
detect
Instructs mount to detect which hash function is in use by examining the file system being mounted, and to write this information into the reiserfs superblock. This is only useful on the first mount of an old format file system.
hashed_relocation
Tunes the block allocator. This may provide performance improvements in some situations.
no_unhashed_relocation
Tunes the block allocator. This may provide performance improvements in some situations.
noborder
Disable the border allocator algorithm invented by Yury Yu. Rupasov. This may provide performance improvements in some situations.
nolog
Disable journalling. This will provide slight performance improvements in some situations at the cost of losing reiserfs's fast recovery from crashes. Even with this option turned on, reiserfs still performs all journalling operations, save for actual writes into its journalling area. Implementation of nolog is a work in progress.
notail
By default, reiserfs stores small files and 'file tails' directly into its tree. This confuses some utilities such as lilo(8). This option is used to disable packing of files into the tree.
replayonly
Replay the transactions which are in the journal, but do not actually mount the file system. Mainly used by reiserfsck.
resize=number
A remount option which permits online expansion of reiserfs partitions. Instructs reiserfs to assume that the device has number blocks. This option is designed for use with devices which are under logical volume management (LVM). There is a special resizer utility which can be obtained from ftp://ftp.namesys.com/pub/reiserfsprogs.

Mount options for romfs

None.

Mount options for smbfs

Just like nfs, the smbfs implementation expects a binary argument (a struct smb_mount_data) to the mount system call. This argument is constructed by smbmount(8) and the current version of mount (2.12) does not know anything about smbfs.

Mount options for sysv

None.

Mount options for tmpfs

The following parameters accept a suffix k, m or g for Ki, Mi, Gi (binary kilo, mega and giga) and can be changed on remount.

size=nbytes
Override default maximum size of the filesystem. The size is given in bytes, and rounded down to entire pages. The default is half of the memory.
nr_blocks=
Set number of blocks.
nr_inodes=
Set number of inodes.
mode=
Set initial permissions of the root directory.

Mount options for udf

udf is the "Universal Disk Format" filesystem defined by the Optical Storage Technology Association, and is often used for DVD-ROM. See also iso9660.

gid=
Set the default group.
umask=
Set the default umask. The value is given in octal.
uid=
Set the default user.
unhide
Show otherwise hidden files.
undelete
Show deleted files in lists.
nostrict
Unset strict conformance.
iocharset
Set the NLS character set.
bs=
Set the block size. (May not work unless 2048.)
novrs
Skip volume sequence recognition.
session=
Set the CDROM session counting from 0. Default: last session.
anchor=
Override standard anchor location. Default: 256.
volume=
Override the VolumeDesc location. (unused)
partition=
Override the PartitionDesc location. (unused)
lastblock=
Set the last block of the filesystem.
fileset=
Override the fileset block location. (unused)
rootdir=
Override the root directory location. (unused)

Mount options for ufs

ufstype=value
UFS is a file system widely used in different operating systems. The problem are differences among implementations. Features of some implementations are undocumented, so its hard to recognize the type of ufs automatically. That's why the user must specify the type of ufs by mount option. Possible values are:
old
Old format of ufs, this is the default, read only. (Don't forget to give the -r option.)
44bsd
For filesystems created by a BSD-like system (NetBSD,FreeBSD,OpenBSD).
sun
For filesystems created by SunOS or Solaris on Sparc.
sunx86
For filesystems created by Solaris on x86.
hp
For filesystems created by HP-UX, read-only.
nextstep
For filesystems created by NeXTStep (on NeXT station) (currently read only).
nextstep-cd
For NextStep CDROMs (block_size == 2048), read-only.
openstep
For filesystems created by OpenStep (currently read only). The same filesystem type is also used by Mac OS X.
onerror=value
Set behaviour on error:
panic
If an error is encountered, cause a kernel panic.
[lock|umount|repair]
These mount options don't do anything at present; when an error is encountered only a console message is printed.

Mount options for umsdos

See mount options for msdos. The dotsOK option is explicitly killed by umsdos.

Mount options for vfat

First of all, the mount options for fat are recognized. The dotsOK option is explicitly killed by vfat. Furthermore, there are

uni_xlate
Translate unhandled Unicode characters to special escaped sequences. This lets you backup and restore filenames that are created with any Unicode characters. Without this option, a '?' is used when no translation is possible. The escape character is ':' because it is otherwise illegal on the vfat filesystem. The escape sequence that gets used, where u is the unicode character, is: ':', (u & 0x3f), ((u>>6) & 0x3f), (u>>12).
posix
Allow two files with names that only differ in case.
nonumtail
First try to make a short name without sequence number, before trying name~num.ext.
utf8
UTF8 is the filesystem safe 8-bit encoding of Unicode that is used by the console. It can be be enabled for the filesystem with this option. If 'uni_xlate' gets set, UTF8 gets disabled.
shortname=[lower|win95|winnt|mixed]

Defines the behaviour for creation and display of filenames which fit into 8.3 characters. If a long name for a file exists, it will always be preferred display. There are four modes:

lower
Force the short name to lower case upon display; store a long name when the short name is not all upper case.
win95
Force the short name to upper case upon display; store a long name when the short name is not all upper case.
winnt
Display the shortname as is; store a long name when the short name is not all lower case or all upper case.
mixed
Display the short name as is; store a long name when the short name is not all upper case.

The default is "lower".

Mount options for usbfs

devuid=uid and devgid=gid and devmode=mode
Set the owner and group and mode of the device files in the usbfs file system (default: uid=gid=0, mode=0644). The mode is given in octal.
busuid=uid and busgid=gid and busmode=mode
Set the owner and group and mode of the bus directories in the usbfs file system (default: uid=gid=0, mode=0555). The mode is given in octal.
listuid=uid and listgid=gid and listmode=mode
Set the owner and group and mode of the file devices (default: uid=gid=0, mode=0444). The mode is given in octal.

Mount options for xenix

None.

Mount options for xfs

biosize=size
Sets the preferred buffered I/O size (default size is 64K). size must be expressed as the logarithm (base2) of the desired I/O size. Valid values for this option are 14 through 16, inclusive (i.e. 16K, 32K, and 64K bytes). On machines with a 4K pagesize, 13 (8K bytes) is also a valid size. The preferred buffered I/O size can also be altered on an individual file basis using the ioctl(2) system call.
dmapi " / " xdsm
Enable the DMAPI (Data Management API) event callouts.
logbufs=value
Set the number of in-memory log buffers. Valid numbers range from 2-8 inclusive. The default value is 8 buffers for filesystems with a blocksize of 64K, 4 buffers for filesystems with a blocksize of 32K, 3 buffers for filesystems with a blocksize of 16K, and 2 buffers for all other configurations. Increasing the number of buffers may increase performance on some workloads at the cost of the memory used for the additional log buffers and their associated control structures.
logbsize=value
Set the size of each in-memory log buffer. Valid sizes are 16384 (16K) and 32768 (32K). The default value for machines with more than 32MB of memory is 32768, machines with less memory use 16384 by default.
logdev=device and rtdev=device
Use an external log (metadata journal) and/or real-time device. An XFS filesystem has up to three parts: a data section, a log section, and a real-time section. The real-time section is optional, and the log section can be separate from the data section or contained within it. Refer to xfs(5).
noalign
Data allocations will not be aligned at stripe unit boundaries.
noatime
Access timestamps are not updated when a file is read.
norecovery
The filesystem will be mounted without running log recovery. If the filesystem was not cleanly unmounted, it is likely to be inconsistent when mounted in norecovery mode. Some files or directories may not be accessible because of this. Filesystems mounted norecovery must be mounted read-only or the mount will fail.
nouuid
Ignore the filesystem uuid. This avoids errors for duplicate uuids.
osyncisdsync
Make writes to files opened with the O_SYNC flag set behave as if the O_DSYNC flag had been used instead. This can result in better performance without compromising data safety. However if this option is in effect, timestamp updates from O_SYNC writes can be lost if the system crashes.
quota / usrquota / uqnoenforce
User disk quota accounting enabled, and limits (optionally) enforced.
grpquota / gqnoenforce
Group disk quota accounting enabled and limits (optionally) enforced.
sunit=value and swidth=value
Used to specify the stripe unit and width for a RAID device or a stripe volume. value must be specified in 512-byte block units. If this option is not specified and the filesystem was made on a stripe volume or the stripe width or unit were specified for the RAID device at mkfs time, then the mount system call will restore the value from the superblock. For filesystems that are made directly on RAID devices, these options can be used to override the information in the superblock if the underlying disk layout changes after the filesystem has been created. The swidth option is required if the sunit option has been specified, and must be a multiple of the sunit value.

Mount options for xiafs

None. Although nothing is wrong with xiafs, it is not used much, and is not maintained. Probably one shouldn't use it. Since Linux version 2.1.21 xiafs is no longer part of the kernel source.

the Loop Device

One further possible type is a mount via the loop device. For example, the command

mount /tmp/fdimage /mnt -t msdos -o loop=/dev/loop3,blocksize=1024

will set up the loop device /dev/loop3 to correspond to the file /tmp/fdimage, and then mount this device on /mnt.

This type of mount knows about three options, namely loop, offset and encryption, that are really options to losetup(8). (These options can be used in addition to those specific to the filesystem type.)

If no explicit loop device is mentioned (but just an option '-o loop' is given), then mount will try to find some unused loop device and use that. If you are not so unwise as to make /etc/mtab a symbolic link to /proc/mounts then any loop device allocated by mount will be freed by umount. You can also free a loop device by hand, using 'losetup -d', see losetup(8).

Return Codes

mount has the following return codes (the bits can be ORed):

  1. success
  2. incorrect invocation or permissions
  3. system error (out of memory, cannot fork, no more loop devices)
  4. internal mount bug or missing nfs support in mount
  5. user interrupt
  6. problems writing or locking /etc/mtab
  7. mount failure
  8. some mount succeeded

Files

/etc/fstab
file system table
/etc/mtab
table of mounted file systems
/etc/mtab~
lock file
/etc/mtab.tmp
temporary file
/etc/filesystems
a list of filesystem types to try

See Also

mount(2), umount(2), fstab(5), umount(8), swapon(8), nfs(5), xfs(5), e2label(8), xfs_admin(8), mountd(8), nfsd(8), mke2fs(8), tune2fs(8), losetup(8)

Bugs

It is possible for a corrupted file system to cause a crash.

Some Linux file systems don't support -o sync and -o dirsync (the ext2, ext3, fat and vfat file systems do support synchronous updates (a la BSD) when mounted with the sync option).

The -o remount may not be able to change mount parameters (all ext2fs-specific parameters, except sb, are changeable with a remount, for example, but you can't change gid or umask for the fatfs).

Mount by label or uuid will work only if your devices have the names listed in /proc/partitions. In particular, it may well fail if the kernel was compiled with devfs but devfs is not mounted.

It is possible that files /etc/mtab and /proc/mounts don't match. The first file is based only on the mount command options, but the content of the second file also depends on the kernel and others settings (e.g. remote NFS server. In particular case the mount command may reports unreliable information about a NFS mount point and the /proc/mounts file usually contains more reliable information.)

Checking files on NFS filesystem referenced by file descriptors (i.e. the fcntl and ioctl families of functions) may lead to inconsistent result due to the lack of consistency check in kernel even if noac is used.

'Linux 일반' 카테고리의 다른 글

vi 명령어  (0) 2011.01.12
Makefile 문법법  (0) 2011.01.12
diff/patch 사용하기  (0) 2011.01.12
VirtualBox 설정 후 Windows 에서 USB 잡기  (0) 2011.01.12
pc용 개발환경 세팅(jdk, eclipse, android sdk설치)  (0) 2011.01.12

# diff -urN aa/ bb/ > cc-patch



# gzip cc-patch



/// .

# gzip -dc cc-patch.gz | patch -p1

'Linux 일반' 카테고리의 다른 글

Makefile 문법법  (0) 2011.01.12
ext3 mount man page  (0) 2011.01.12
VirtualBox 설정 후 Windows 에서 USB 잡기  (0) 2011.01.12
pc용 개발환경 세팅(jdk, eclipse, android sdk설치)  (0) 2011.01.12
ubuntu에서 usbdl 사용하기  (0) 2011.01.11

효율적인 모바일앱의 작성은 항상 쉽지 않다. 특 히, 안 드로이드처럼 Dalvik garbage collector 의해 자동으로 메모리가 관리되는 경우 충분히 주의하지 않으면 성능이슈가 발생할 수밖에 없다

성능에 민감한 코드들(layout생성, view시스템의 그리기, 게임의 로직부분)은 필연적으로 비용을 초래한다. 너무 많은 메모리 할당후에는 당신의 앱은 메모리를 해재하도록 잠시 멈출수 있다. 대부분의 경우 사용자가 느끼지 못할정도로 gc는 이루어지는 반면에 리스트를 scroll하거나 게임에서 적을 물리치거나 하는 경우 심각한 성능과 응답성의 저하를 느낄수 있다. 100~200ms정도 gc시간이 걸리는 것은 일반적인 상황은 아니다. 부드러운 애니매이션의 경우 각 프레임이 16~33ms정도의 속도가 필요하다. 초당 10프레임정도로만 떨어져도 사용자는 문제를 느끼게 된다.

대개의 경우 gc는 tons of small, short-lived object, 일부 garbage collector때문에 발생한다. 그리고 그런 object의 collection을 최적화할 수 있으며 그렇게 해서 애플리케이션의 좀더 덜 방해받게 할 수 있다. 안드로이드의 garbage collector는 불행히도 이러한 성능최적화등을 할 수 없다. 

더보기

잦 은 gc를 피해가도록 해주기 위해, 안드로이드 SDK는 allocation tracker라는 툴을 포함시켰다. DDMS의 일부기능으로 되어 있으며 디버깅목적으로 이미 사용하고 있다. 이 툴을 사용하려면 SDK에 포함되어 있는 DDMS를 먼저 실행한다. 이클립스버전의 DDMS에는 아직 지원되지 않는다.

DDMS가 실행되면 해당 애플리케이션 프로세스를 선택하고 Allocation Tracker탭을 클릭하라. 새로운 뷰에서 Start Tracking을 클릭하면 분석하고자 하는 애플리케이션을 선택한다. 준비가 되었다면 Get Allocations를 선택하가. 할당된 object들이 첫번째 테이블에 리스트될것이다. 보여지는 한 line을 선택하면 두번째 테이블에 애플리케이션에 할당된 stack이 보여진다. 어떤 타입의 object들이 할당되었는지는 물론이고 포함된 스래드, 클래스, 파일의 라인까지 표시된다. 아래 스크린샷은 Shelves앱의 listView를 스크롤하는 동안의 할당상태를 보여준다.

성 능에 영향을 주는 부분을 모두 제거할 필요가 없다고 하더라도 코드에서 중요한 이슈를 확인하는데 도움이 될것이다.  예를 들면 내가 보아온 많은 애플리케이션에서 draw시마다 매번 Paint 객체를 새로 생성한다. 이 Paint객체를 하나의 인스탄스로 관리하는 것 만으로 성능이슈를 간단히 개선할 수 있다. 나는 Android source code를 살펴볼것을 강력하게 권고한다. 이유는 성능을 끌어올리기 위해 어떤 기술을 사용하였는지 볼수 있기 때문이다. 그리고 객체의 재사용에 대한 안드로이드가 제공하는 API들을 발견하게 될것이다.

+ Recent posts