'OS/리눅스 & 유닉스'에 해당되는 글 130건

  1. 2012.03.16 Bash Color Chart
  2. 2012.03.16 IBM nmon FAQ
  3. 2012.03.16 Unix Programming Frequently Asked Questions
  4. 2012.03.16 UNIX 명령어
  5. 2012.03.16 Using the "truss" command in Solaris
  6. 2012.03.14 Thread Functions for POSIX, Solaris and Windows NT
  7. 2012.02.21 sigwaitinfo
  8. 2012.02.16 pthread_kill
  9. 2012.02.13 grep 명령어
  10. 2012.02.13 grep, egrep, fgrep & 정규식

Bash Color Chart

OS/리눅스 & 유닉스 2012. 3. 16. 18:36

 http://www.arwin.net/tech/bash.php 

#!/bens/bash

This is a collection of bash environment settings and useful information that I like to keep handy for when I'm setting up a new shell environment.

It's an ever-growing work in progress that I add to as I discover new customizations (and have the time to document them).

My main focus here is customizing the colors in bash prompts and in 'ls' output. I'm a fairly visual person, so I like different systems to have different colors in their prompts. It's helpful when you have several ssh sessions open across multiple machines and want to easily identify which machine you're looking at. Reboot the wrong machine once or twice and you start to appreciate the visual hints :)

Bash Color Chart(back to top)

Black 0;30 Dark Gray 1;30 Blue 0;34 Light Blue 1;34 Green 0;32 Light Green 1;32 Cyan 0;36 Light Cyan 1;36 Red 0;31 Light Red 1;31 Purple 0;35 Light Purple 1;35 Brown 0;33 Yellow 1;33 Light Gray 0;37 White 1;37

Bash Prompts(back to top)

Two Line Prompt

# with time export PS1='\n\[\e[31;1m\]CWD\[\e[0m\]:\[\e[36;1m\]\w\n\[\e[32;1m\]\@:\u@\h\[\e[0m\]\$ ' # without the time: export PS1='\n\[\e[31;1m\]CWD\[\e[0m\]:\[\e[36;1m\]\w\n\[\e[32;1m\]\u@\h\[\e[0m\]\$ '

black and red

export PS1='\[\033[1;31m\](\[\033[0;37m\]\u\[\033[1;31m\]@\h\[\033[1;31m\]:\[\033[1;36m\]\w\[\033[1;31m\])\[\033[1;36m\]\$ \[\033[0;37m\]' # alternate for root, same but green username: export PS1='\[\033[1;32m\](\[\033[1;32m\]\u\[\033[1;31m\]@\h\[\033[1;31m\]:\[\033[1;36m\]\w\[\033[1;32m\])\[\033[1;36m\]\$ \[\033[0;37m\]'

ubuntu

# ubuntu sets a pretty nice prompt by default (if you have a TERM=xterm-color (I modified the \w to be purple (35) instead of blue (34) export PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;35m\]\w\[\033[00m\]\$ '

Smiley Face Prompt

# smiley face prompt: # From: CommandLineFu PS1="\`if [ \$? = 0 ]; then echo \e[33\;40m\\\^\\\_\\\^\e[0m; else echo \e[36\;40m\\\-\e[0m\\\_\e[36\;40m\\\-\e[0m; fi\` \u \w:\h) "

Window/Tab Titles for terminal emulators (works with iTerm in OS X)

# If this is an xterm set the title to user@host:dir case "$TERM" in xterm*|rxvt*) PS1="\[\e]0;\u@\h: \w\a\]$PS1" ;; *) ;; esac

This was borrowed from a standard .bashrc on Ubuntu. It's more efficient than setting $PROMPT_COMMAND and it sends the appropriate escape codes to iTerm to set the tab title.

Without this, if you ssh to a remote machine that sets a title, that title will stick around even after your ssh session has ended. Meaning you'll be back on your local machine but the tab/window title will still reflect the last remote machine you were logged in to. Confusing...

Dir Colors(back to top)

Linux

# LS_COLORS (make directories purple instead of dark blue . The rest are what ubuntu shipped w/by default) LS_COLORS='no=00:fi=00:di=01;35:ln=01;36:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:su=37;41:sg=30;43:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.gz=01;31:*.bz2=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.avi=01;35:*.fli=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.flac=01;35:*.mp3=01;35:*.mpc=01;35:*.ogg=01;35:*.wav=01;35:'; export LS_COLORS
Show Extra

Mac OS X (BSD)

# Dir colors (barwin custom) # http://www.mactips.org/archives/2005/08/02/color-your-os-x-command-prompt/ # http://www.macosxhints.com/article.php?story=20031025162727485 export CLICOLOR=1 export LSCOLORS=FxFxCxDxBxegedabagacad

Aliases(back to top)

alias ll='ls -la' alias cd..='cd ..' alias vi=vim alias svi='sudo vi' alias vis='vim "+set si"' alias apt-get="sudo apt-get" alias rm='rm -i' alias mv='mv -i' alias cp='cp -i' alias sha1='openssl sha1' alias grep='grep --color=auto'

Valid XHTML 1.0 Transitional

Valid CSS!

'OS > 리눅스 & 유닉스' 카테고리의 다른 글

아파치 접속자 수  (0) 2012.03.20
ANSI Escape Sequences: Colours and Cursor Movement  (0) 2012.03.16
IBM nmon FAQ  (0) 2012.03.16
Unix Programming Frequently Asked Questions  (0) 2012.03.16
UNIX 명령어  (0) 2012.03.16
:

IBM nmon FAQ

OS/리눅스 & 유닉스 2012. 3. 16. 17:08
http://www.ibm.com/developerworks/wikis/display/WikiPtype/nmon+FAQ

Summary of the questions:

  • Question 1: Which nmon for my version of AIX or Linux?
  • Question 2: nmon crash shortly after starting a data capture please send me the next version?
  • Question 3: I have a problem with nmon running on AIX 4.0.3 (or any really old AIX versions)?
  • Question 4: All I get is "nmon not found"?
  • Question 5: Can you add the monitoring tape drive on AIX?
  • Question 6: Can I get the adapters stats from other tools?
  • Question 7: When I start nmon 9 on a system that it use to run fine I know get an error message?
  • Question 8: What is the most reported error for nmon?
  • Question 9: Can you add the monitoring of process priority?
  • Question 10: on AIX, nmon 9 does not run, please fix?
  • Question 11: Can I decide the filename it saves data too?
  • Question 12: What is the default output filename?
  • Question 13: I want nmon output piped into a further command, how?
  • Question 14: Why do you support all these old unsupported AIX versions?
  • Question 15: What if I want support?
  • Question 16: Why don't you add a Java front end to nmon and get graphical output?
  • Question 17: The command line options don't seem to work right for file capture?
  • Question 18: What is paging to a filesystem?
  • Question 19: Where can I get nmon and further information?
  • Question 20: nmon crashes after about 200 snapshots on AIX?
  • Question 21: TOP process stats get switched on when I request Asynchronous I/O stats?
  • Question 23: nmon2rrd fails, please fix it?
  • Question 24: NANQ and INF?
  • Question 25: nmon and AIX commands do not agree?
  • Question 26: nmon reports more than 100% for a process - clearly it is wrong?
  • Question 27: On AIX the disk adapter are wrong?
  • Question 28: on AIX the adapter busy goes over 100%. That is impossible surely?
  • Question 29: What about nmon for HP/UX, Solaris on Sparc or x86 or Linux on Itanium?
  • Question 30: What about nmon for Windows?
  • Question 31: Seeing double the number of CPUs?
  • Question 32: 0509-036 Cannot load program /usr/lib/drivers/nfs_kdes.ext ?
  • Question 33: Hello, I am new to UNIX and want to tune AIX, what do you recommend?
  • Question 34: CPU wait is too high, how can I reduce it?
  • Question 35: On AIX, free memory is near zero, how do I free more memory?
  • Question 36: How can I set numperm better?
  • Question 37: What format is the nmon output file?
  • Question 38: I have collected once a second for 8 hours but I can't get the Analyser to work?
  • Question 39: nmon does not work on my Linux machine!!
  • Question 40: When do we get nmon 10 for Linux?
  • Question 41: The boxes and lines in nmon do not work right online with: DTterm, xterm, rvxt, putty, VNC, (whatever you have)?
  • Question 42: I have 2400 disk (small SAN LUNs) and nmon is slow to collect the stats from so many, can you help?
  • Question 43: Adapter stats and IOADAPT is not saved to the nmon file seems to be missing with AIX 5.1?
  • Question 44: What is CharIO (a column of the TOP processes stats)?
  • Question 45: On Linux the disk stats are all doubled?
  • Question 46: On AIX the disk seem to be mostly on the first adapter?
  • Question 47: On nmon for Linux the CPU Wait for IO number is zero or odd?
  • Question 48: On nmon for Linux the paging details are missing and the PAGE lines for the capture to file are missing.
  • Question 49: I want to collect data every second and then see weekly and monthly reports. How?
  • Question 50: nmon will not start on AIX 5.1 due to a libperfstat error?
  • Question 51: How do I work out the Physical CPU use on Linux on POWER for shared processor LPARs?
  • Question 52: The Disk Busy stats are missing on AIX
  • Question 53: Sort order problems with massive nmon output files.
  • Question 54: AIX 5.3 updated but then nmon gives "Illegal instruction(coredump)"
  • Question 54: AIX 5.3 updated but then nmon gives "Assert Failure"
  • Question 55: On AIX 5.3 ML6, nmon output files contain zeros, missing CPU stats, corrupt ZZZ lines and "nfs" strings found in the stats
  • Question 56: Does nmon capture point in time stats or averages?
  • Question 57: Why is the Process memory percentage zero? (same for System and User percent)
  • Question 100: When will nmon collect data from lots of machines or LPARs?
  • Question 101: When will nmon collect data like "topas -C"?
 

'OS > 리눅스 & 유닉스' 카테고리의 다른 글

ANSI Escape Sequences: Colours and Cursor Movement  (0) 2012.03.16
Bash Color Chart  (0) 2012.03.16
Unix Programming Frequently Asked Questions  (0) 2012.03.16
UNIX 명령어  (0) 2012.03.16
Using the "truss" command in Solaris  (0) 2012.03.16
:

Unix Programming Frequently Asked Questions

OS/리눅스 & 유닉스 2012. 3. 16. 15:30
http://www.steve.org.uk/Reference/Unix/faq_1.html

Unix Programming Frequently Asked Questions


'OS > 리눅스 & 유닉스' 카테고리의 다른 글

Bash Color Chart  (0) 2012.03.16
IBM nmon FAQ  (0) 2012.03.16
UNIX 명령어  (0) 2012.03.16
Using the "truss" command in Solaris  (0) 2012.03.16
Thread Functions for POSIX, Solaris and Windows NT  (0) 2012.03.14
:

UNIX 명령어

OS/리눅스 & 유닉스 2012. 3. 16. 14:28

UNIX 명령어


1. addbib - 도서목록 형식의 데이터베이스를 만들거나, 확장


2. apropos - 사용설명서의 키워드 검색


3. ar - 라이브러리 만들기, 관리

아카이브 화일에 있는 화일의 그룹들을 유지 관리하는 명령어

문법 ar [drqtpmx] [vuaiblc] afile files ...

options

d 아카이브 화일에 있는 특정화일을 삭제

r 아카이브 화일에 있는 화일을 교체 ; 문자 n 와 함께 쓰면 수정되는 날짜보다 뒤의 화일만을 교체

q 특정 화일을 아카이브 화일의 맨 뒤에 첨가

t 아카이브 화일내의 목록을 출력

p 아카이므 화일내의 지정된 화일 내용을 출력

m 아카이브 화일의 맨 끝에 특정 화일을 이동시킨다 ; 인수 a, b 또는

i와 함께 사용하면 posname으로 위치를 지정할 수 있다

x 특정화일을 추출

c afile을 생성

l system 내의 임시 directory인 /tmp 대신에 local directory에 있는 임시 화일을 둔다

v 새로운 아카이브 화일 생성에서 기술된 정보를 화일별로 출력. 인수

t와 함께 사용하며 화일에 관한 모든 정보의 목록을 출력할 수 있으며 인수 x와 함께 사용하면 화일명이 먼저 출력

afile 아카이브 filename


4. at, batch - 원하는 시간에 원하는 명령을 실해하게 하는 명령

사용자가 원하는 시간에 프로그램 스케쥴링을 할 수 있는 명령어. 또한 앞으로 사용될 작업들을 확인해 볼수 있으며(atq), 취소(atrm)도 가능하다. 주로 이것은 시스템 관리자가 시스템을 정리하고자 할 때 이용하고 있는 사용자에게 메시지를 전달하는 등 비교적 규칙적으로 서버에서 일어날 수 있는 일에 자주 사용된다.

일정 시간이 지난후에 명령어를 실행 시깁니다. 따라서 자리를 비우고 30분후에 시스템을 다운 시킨다든지 하는 등 명령어에 타이머를 달수 있습니다.

옵션 -l at queue 를 보여 줍니다.

-d 번호 queue 에서 삭제 합니다. 즉 예약 명령 취소

ex) 10:20 분에 시스템을 정지 하는 것을 예약하고 싶은 경우

#at 10:20 ; 10:20 분을 줍니다.

at>halt ; 프롬프트가 at> 로 바뀌면, halt 명령을 예약합니다. .

ctrl-D ; ctrl+D 로 빠져나옵니다. ( ctrl-C, ctrl-Z 로 빠져나오면 예약이 안 됩니다. )


5. awk - 패턴 검색과 언어 처리

program file에서 기술된 pattern들중 일치되는 line 을 찾기 위해 입력 화일을 검색하는 명령어

문법 awk [-Fc] [profile] [file] ...

또는

awk [-Fc] [-f profile] [file] ...

options

-Fc 입력필드의 구분기호로서 c를 이용

-f progam file로서 다음 인수 사용


6. banner - 큰 글자(배너) 만들기

10문자이내의 문자열을 확대문자로 표준출력\

문법 banner string


7. basename - 경로 이름에서 마지막에 있는 이름만 출력


8. bdiff - 매우 큰 화일을 비교하는 diff 명령어

문법 bdiff file1 file2 [u] [-s]

options

file1,file2 비교하는 filename

n segment 수를 지정하여 생략시 default로 3500임

-s 진단적 message를 표준 출력하지 않는다


9. bfs - 매우 큰 화일을 scan하는 명령어

문법 bfs [-] name

options

- file의 크기를 출력하지 않음

name 읽기만 하는 화일을 scan 할 때 사용되며 name 은 filename


10. biff - 자신에게 편지가 배달되면 알려주는 명령


11. bin-mail, binmail - 예전에 사용한 전자우편 프로그램


12. cal - 달력보기


13. calendar - 간단한 일정표

현재 directory 내의 calendar file로부터 매일의 메모를 print하는 명령어

문법 calendar [-]

options

- login directory에 calendar file을 가지는 각 사용자에 이 화일 중의 오늘과 내일 날짜를 포함하는 라인을 전자우편(mail)으로 보낸다


14. cat - 파일 병합과 내용 보기

파일의 내용을 화면에 출력하거나 파일을 만드는 명령( 도스의 TYPE명령)

% cat filename


15. cb - 간단한 C 프로그램 beautifier


16. cc - C 컴파일러

17. cd - 작업 디렉토리 바꾸기

디렉토리를 변경

% cd cgi-bin : 하부 디렉토리인 cgi-bin으로 들어감.

% cd .. : 상위디렉토리로 이동

% cd 또는 cd ~ : 어느곳에서든지 자기 홈디렉토리로 바로 이동

% cd /webker : 현재 작업중인 디렉토리의 하위나 상위 디렉토리가

아닌 다른 디렉토리(webker)로 이동하려면 /로 시작해서 경로이름을 입력하면 된다.


18. checknr - nroff 또는 troff 입력 파일 검사; 오류를 보여준다


19. chgrp - 파일의 사용자 그룹 바꾸기


20. chmod - 파일의 접근 권한 바꾸기

화일 permission 변경

유닉스에서는 각 화일과 디렉토리에 사용권한을 부여.

예) -rwxr-xr-x guestbookt.html

rwx :처음 3개 문자 = 사용자 자신의 사용 권한

r-x :그다음 3개 문자 = 그룹 사용자의 사용 권한

r-x :마지막 3개 문자 = 전체 사용자의 사용 권한


읽기(read)---------- 화일 읽기 권한

쓰기(write)---------- 화일 쓰기 권한

실행(execution)---------- 화일 실행 권한

없음(-)---------- 사용권한 없음


명령어 사용법

chmod [변경모드] [파일]


% chmod 666 guestbook.html

: test.html 화일을 자신에게만 r,w,x 권한을 줌

% chmod 766 guestbook.html

: 자신은 모든 권한을 그룹사용자와,전체사용자에게는 읽기와 쓰기 권한만 줌


21. clear - 터미날 화면 깨끗이 하기


22. cmp - 두 파일을 바이트 단위로 비교

두 개의 화일 내용을 비교하는 명령어

문법 Cmp [-l] [-s] file1 file2

options

-l 두 화일 내용을 비교함에 있어 틀린곳마다 byte 수 (10진수)와 틀린 byte 수(8진수)를 출력

-s 틀린 화일의 내용을 출력하지 않고 return code 만 변환한다


23. colcrt - troff 파일의 밑줄 속성 문자 처리


24. comm - 지정 두파일의 줄 단위 비교와 그 처리

두 개의 정렬(sort)된 화일에서 공통된 line을 선택하거나 삭제하는 명령어

문법 comm [-123] file1 file2

options

1 file1에만 있는 line을 출력하지 않는다

2 file2에만 있는 line을 출력하지 않는다

3 file1, file2 양쪽 화일에 있는 line을 출력하지 않는다


25. compress, uncompress, zcat - 파일 압축관련 유틸리티들

확장자 .Z 형태의 압축파일 생성

% compress [파일명] : 압축시

% uncompress [파일명] : 해제시


26. cp - 파일 복사

화일 복사(copy)

% cp index.html index.old

: index.html 화일을 index.old 란 이름으로 복사.

% cp /etc/*.* .

: etc 디렉토리내의 모든 화일을 현 디렉토리로 복사


27. cpio - copy file archives in and out

아카이브 화일을 복사하여 입출력하는 명령어

문법 cpio -o [abcv]

cpio -i [Bdmtuvsb] [patterns]

cpio -p [adlmv] directory

options

-o 복사 출력: 화일을 path명과 정보 상태를 함께 출력

-i 복사 입력: 표준 입력 화일로 부터 pattern에 일치하는 화일을 추출

-p *directory 내에 file 을 조건부로 작성하고 복사

a *file 복사후 입력 화일의 최종 접근 시간을 reset한다

B 입출력을 5,120 byte의 레코드로 블럭화한다

c ASCII 문자로 헤드 정보를 쓴다

d 필요에 따라 directory를 생성

m 존재하는 최종 화일 수정 시각을 보존

r 대화 문법으로 화일명을 변경

t 입력 화일명 목록을 출력하여 화일은 작성되지 않는다

u 무조건 복사

v 화일명 목록을 출력


28. cpp - C 언어 전처리기


29. crontab - 지정된 시간에 유저의 crontab 파일을 관리하는 명령어  

지정한 화일을 입력으로 받아 user의 크론탭 화일을 관리 및 directory로 복사하는 명령어

문법 crontab [file]

options

-r user crontab을 crontab directory로 부터 삭제

-l 호출한 user crontab fule을 출력

file 등록되는 화일명을 지정


30. csh - C 문법과 비슷한 쉘 스크립트 문법과 기타 여러 기능이 내장된 쉘


31. ctags - ex 나 vi 편집기에서 사용될 tag 파일을 만드는 명령


32. cut - 파일이 각 line에서 선택된 필드를 절단하는 명령어

화일이 각 line에서 선택된 필드를 절단하는 명령어

문법 cut -clist [file1 file2 ...]

cut -flist [-d char] [-s] [file1 file2 ...]

options

list - 사용으로 페이지 범위를 지정할수 있으며 정수의 필드 번호를 컴마로 분리하고 증가순서로 나열

clist 문자위치를 지정

(예로서, -(1-72)는 각 line에서 첫 72문자이다)

-d char -d의 문자는 필드구분 문자이며 -f 옵션에서만 필요

flist 구분문자에 의해 분리되는 필드 목록

(예로서, -f1,7은 첫번째와 일곱번째 필드를 복사)

-s 필드 구분문자가 없는 line은 무시


33. date - 시스템 시간 보기나 지정하기


34. dbx - 소스 수준의 디버거


35. deroff - nroff, troff, tbl, eqn 관련 내용 지움


36. df - disk free: 디스크의 남은 용량 보기

이용가능한 디스크블럭수를 출력하는 명령어

문법 df [-f] [-t] [file sysytem]

options

-f 디스크내의 자유리스트내의 정확한 블럭수를 출력

-t 사용가능 블럭 및 i-node와 할당된 전체블럭과 i-node가 출력


37. diff - 두 파일의 차이점 비교

두개의 화일중에서 다른 라인을 출력하는 명령어

문법 diff [-befh] file1 file2

options

-b 비교할 때 라인의 마지막에 있는 탭(tab)과 공백을 무시

-e file1으로부터 file2를 재생성. ed 편집을 위한 a,c 그리고 d 명령어의 script를 만든다

-f 비슷한 script를 만들지만 역순이기 때문에 ed 편집에서는 사용할 수 없다

-h 정밀도가 없어도 빠른 속도를 처리하고자 할 때 사용하며 -e와 -f와 함께 사용할수 없다

문법 diff3 [-ex3] file1 file2 file3

options

-e file1에 file2와 file3의 차이 비교를 기록

-x file1에 3개 화일 모두의 차이 비교를 기록

-3 file1에 file3과 차이 비교되는 부분만 기록


38. dircmp - 디렉토리를 비교하는 명령어

문법 dircmp [-dsw] directory1 directory2

options

-d 두 directory내의 화일명을 비교후 그 차이점을 diff문법으로 출력

-s 비교 일치된 화일에 대한 메세지 출력 안함

-Wn 출력되는 화면의 폭(n)을 변경

**) directory1, directory2는 비교되는 디렉토리명


39. du - disk used : 디스크 사용량 보기

디스크 사용을 요약 출력하는 명령어

문법 du [-ars] [files]

options

-a 각 화일에 대한 entry 출력

-r 읽을 수 없는 directory 또는 열 수(open) 없는 화일에 대해 메세지

를 출력

-s 이름으로 지정된 각각에 대한 총계 블럭수만을 출력


40. echo - 인자를 표준 출력으로 출력

echo명령어는 외부 프로그램과 내부 쉘명령어 사이에 있으며 echo의 인수는 공백에 의해 구분되어지며 new line으로 종료하는 각 인수를 화면에 표준출력하는 명령어

문법 echo [-n] [arg] ...

options

-n new line이 없는 것은 추가로 출력


41. ed, red - 기본 줄 편집기

표준 텍스트 편집기 (라인 편집기)

문법 ed [-] [-x] [file]

options

- 문자 e,r과 w의 명령어의 출력을 없앤다

-x x 명령어는 암호와 선택 항목 인수이다


42. env - UNIX 명령어를 수행하기 위한 환경을 설정하는 명령어

문법 env [-] [name=value] ... [command arg]

options

- 기존 환경을 무시하고 지정된 환경으로 명령어를 수행

name=value 명령 수행 전의 원래 환경을 지정

command arg 수행하고자 하는 명령어 지정



43. eqn, neqn, checkeq - 수식 표현 포멧 도구


44. error - 컴파일러 오류 메시지 목록


45. ex, edit, e - 줄 편집기

ed 기능을 강화한 텍스트 편집기

문법 ex [-] [-trRV] [+command] name ...

options

- 대화형 사용자를 위해 feed-back을 억제

-t tag tag를 갖는 화일을 편집후 편집기를 그 화일의 위치에 지정

-r file file을 복구

R 읽기 허가만 된 모드로 한다

+ command 지정한 명령어를 수행하고 편집


46. expand, unexpand - TAB 문자를 공백문자로 바꿈, 또는 그 반대로


47. expr - 인자를 수식으로 처리


48. fgrep - 문자열에 따라 화일 검색

문자열에 따라 화일 검색(fgrep [option] string [file .. ) fgrep은 문자열에 따라 화일을 검색하여 지정한 문자열이 있는 모든 행을 출력하며 정규식(영문,숫자,특수문자의 부분집합을 사용하는 식)을 사용 하는 grep와는 차이가 있다.

-b: 각 행의 선두에 그 행이 발견된 블럭번호를 넣어줌.

-c: 일치하는 패턴을 갖고 있는 행의 수 만을 출력함.

-l: 일치하는 행이 있는 화일의 화일명만을 복귀개행으로 구별시켜 출력하는데, 화일내에 패턴이 몇 개나 포함되어 있어도 화일명은 한 개밖에 출력하지 않음.

-n: 각 행의 선두에 화일내의 행번호를 넣음.(1 라인은 1임)

-i: 비교시 소문자와 대문자의 차이를 무시

-v: 일치하는 행을 제외한 모든행을 출력.


49. file - 파일 형식 알아보기

화일 형태를 결정하는 명령어

문법 file [-f] file ...

options

-f 다음 인수를 조사하고 싶은 화일명을 포함하는 화일로 간주


50. find - 파일 찾기

각 경로명에 대해서 계층적 directory를 순환적으로 내림차순으로 불(Boolean)표현식과 일치하는 화일을 찾는 명령어

문법 find pathname-list expression

options

-atime n 만약 화일이 n 날짜 이내에 접근되면 참

-cpio device 현재의 화일은 cpio(1)의 문법(5120byte 레코드)으로 장치에 써넣는다

-ctime n 화일이 n 날짜내에 변경되면 참

-exec cmd 지정한 명령어를 수행하고 종료상태로서 0의 값이 반환되면 참

-group gname 화일에 gname에 포함되어 있으면 참

-links n 화일이 n 개의 링크가 있으면 참

-mtime n 화일이 n 날짜 이내에 수정되면 참

-name file 화일이 현재의 화일명과 일치하면 참

-newer file 현 화일이 인수화일보다 최근에 수정되어 있으면 참

-ok cmd 명령어 라인을 의문부호를 선두에 부과하여 화면에 출력하며 만약 사용자가 y를 칠 경우에만 실행 가능

-perm onum 화일의 허가 그래프가 9진수 onum과 일치하는 경우이면 참

(chmod(1) 참조)

-print 항상 참 ; 현재의 패스명을 출력

-size n 화일의 길이가 n 블럭(블럭당 512byte)이면 참

-type c 화일의 형태가 이면 참이며 여기서 말하는 c는 블럭형태인 특수화일,

문자형 특수화일, 디렉토리, 파이프 또는 일반화일을 각각 b,c,d,p,

또는 f로 표시

-user unname 화일이 사용자 unname에 속하면 참

(expression) 괄호내의 식이 참이면 참


1. 특정파일을 모두 찾아서 각각 "ls -l"하여 정보확인하기

[root@kebia_1 /root]# find / -name .searchfile -exec ls -l {} \;

2. 특정파일을 모두 찾아서 각각 파일내용 확인하기

[root@kebia_1 /root]# find / -name .searchfile -exec cat {} \;


51. finger - 사용자 정보 알아보기

who 명령을 보충하는 명령이 finger입니다. 특정 사용자에 대한 정보를 알려면 finger username(또는 사용자가 다른 컴퓨터에 있으면 finger username@domain)을 입력합니다.


52. fmt, fmt_mail - 간단한 문서나, 편지 포멧 도구


53. fold - 긴 줄 출력 방법 지정


54. ftp - 파일 전송 프로그램


55. gcore - 실행 중인 프로세스의 core 이미지를 구한다.


56. gprof - call-graph profile data(?)를 보여줌


57. grep - 문자열 찾기

화일의 패턴을 검색하는 명령어

문법 grep [option] expression [file]

options

-b 각 라인의 첫머리에 블럭번호를 넣는다

-c 라인에 일치되는 수를 출력

-e expression a로 시작되는 식일 때 사용

-f file 규칙적인 식(grep) 또는 리스트열(fgrep)이 화일로부터 취한다

-l 일치되는 라인의 화일명만 출력

-s 읽지못하는 화일이거나 존재하지 않는 화일에 대한 에러 메세지 출력을 억제

-v 일치되는 라인을 제외한 모든 라인을 출력

-x 정확히 일치되는 라인을 출력 (fgrep만 사용)


58. groups - 사용자의 그룹을 보여줌


59. gzip - 확장자 .gz, .z 형태의 압축파일 생성

확장자 .gz, .z 형태의 압축파일 생성

% gzip [파일명] : 압축시

% gzip -d [파일명] : 해제시


60. head - 파일의 앞 부분 보기

% head -n filename : n줄 만큼 위세서부터 보여줌


61. history - 이전 명령 보기


62. hostname - 현재 시스템 이름을 보여줌


63. imake - makefile 만드는 프로그램


64. indent - C 프로그램 소스 파일을 들여쓰기 하는 포멧 도구


65. install - 파일 설치


66. ipcs - process 상호간의 통신에 대한 상태를 출력하는 명령어

문법 ipcs [-copqt]

options

-c 사용자의 로그인 명과 그룹명을 출력

-o 사용 상황 상태에 대한 정보를 출력

-p 프로세서 번호에 대한 정보를 출력

-q 수행중인 메세지 큐(Queue)에 대한 정보를 출력

-t 시간에 대한 정보를 출력


67. join - 관계형 데이터베이스 연산자


68. kill - 프로세스 죽이기

프로세스를 강제 종료하는 명령어

문법 kill [-signo] process id ...

options

1 hang up

2 인터럽터

3 정지

4 정확하지 않는 명령

5 trace trap

6 IOT

7 EMT

8 부도소수점 expression 발생

9 강제 종료

10 버스 에러

11 세그먼트 위배

12 bad system 콜

13 읽는 사람없이 파이프에 써 넣음

14 경보 신호

15 Software 종료


69. last - 사용자가 마지막 접속 상태를 보여줌


70. ld, ld.so - 링크 편집기, 동적 링크 편집기


71. leave - 자신의 접속 종료 시간을 알려줌


72. less - more 명령의 확장


73. lex - 어휘 분석 프로그램 생성기


74. link - 파일 및 디렉토리 링크 명령어


75. lint - C 프로그램 verifier


76. ln - 파일의 하드, 심벌릭 링크 명령


77. login - 시스템 접속 명령


78. look - 시스템 디렉토리나, 정열된 목록에서 단어 찾기


79. lookbib - 도서목록형 데이타베이스에서 찾기


80. lorder - 오브젝트 라이브러리의 관계 찾기


81. lp, cancel - 인쇄 시작, 취소

특정화일 및 정보를 프린터로 출력하는 명령어

문법 lp [-c] [-d lest] [-m] [-nnumber] [-0 option] [-s] [-t title]

[-w] files

options

-c 프린터가 끝나기전에 화일 변경이 가능하도록 프린트할 화일을 복사

-d dest 프린터 또는 프린터 클라스를 dest로 지정

-n 프린트 후 전자우편을 보낸다

-n number 프린트 할 매수를 지정

-s 메세지 출력을 억제

-w 프린트 후 사용자의 단말장치에 메세지를 보낸다


82. lpq - 인쇄 작업 상황 보기


83. lpr - 인쇄


84. lprm - 인쇄 작업 지우기


85. ls - 디렉토리 내용 보기

directory의 내용을 화면에 출력하는 명령어

문법 ls [-aAcCdDfFgimngrRstuxl] file ...

options

-a .file을 포함한 전 entry를 출력

-A -a option과 유사하지만 .또는 ..을 포함하는 화일은 출력 억제

-c 마지막 변경된 i-node의 시간을 출력

-C 멀티칼럼으로 출력하며 디폴트로는 CRT에 출력

-d directory명만 출력하며 내용은 출력하지 않는다

-D directory만 출력

-f 인수를 directory로 해석하며 각각의 슬롯에 있는 directory 및 file

명을 출력

-F system에 있는 화일이 directory면 /를 실행가능한 화일이면 *를 붙

인다

-g 옵션 -l과 같으나 소유자명이 출력되지 않는다

-i 첫 칼럼에 i-number를 출력

-l 화일 및 directory 상태 정보를 long 문법으로 출력

-m 스트림 문법의 출력

-n 소유자명과 그룹명 대신에 UID 번호와 GID 번호가 출력되는 것을 제

하고는 옵션 -l과 같다

-g 비도형문자를 ?문자로 출력

-r 화일명이나 수정시간을 알파벳 또는 오래된 역순으로 출력

-R 발견되는 sub-directory의 내용을 순환적으로 출력

-s 간접블럭을 내포하는 블럭수를 출력

-t 화일명 대신에 수정된 시간으로 분류

-u -t 또는 -l option으로 분류하는 중에서 최종접근 시간을 사용


86. mail, Mail - 전자 우편 프로그램


87. make - 실행 파일을 만들거나, 특정 작업 파일을 만들 때 사용하는 도구


88. man - 온라인 사용자 설명서를 보는 명령

원하는 명령어의 사용방법을 CRT 화면에서 알고자하는 명령어

문법 man [option ... ] [chapter] title ...


89. mesg - 메시지 수신 상태를 보거나 지정


90. mkdir - 디렉토리 만들기

디렉토리 생성

% mkdir download : download 디렉토리 생성


91. mkstr - C 소스 파일을 참조로 오류 메시지 파일을 만듬.


92. more, page - 텍스트 파일 보기 명령

cat 명령어는 실행을 시키면 한 화면을 넘기는 파일일 경우 그 내용을 모두 볼수가 없다. 하지만 more 명령어를 사용하면 한 화면 단위로 보여줄 수 있어 유용.


% more <옵션>

옵션은 다음과 같습니다.

Space bar : 다음 페이지

Return(enter) key : 다음 줄

v : vi 편집기로 전환

/str : str 문자를 찾음

b : 이전 페이지

q : more 상태를 빠져나감

h : 도움말

= : 현재 line number를 보여줌


93. mount - file system을 mount하는 명령어

file system을 mount하는 명령어

문법 mount [special directory [-r]]

options

special directory에 있는 블럭형 특수장치를 말한다

directory special이나 resource를 위한 적재 directory를 가리킨다

-r special이나 resource를 읽기허가하여 적재하도록 한다


94. mountall - 여러개의 file system을 mount하는 명령어

여러개의 file system을 mount하는 명령어

문법 mountall [-] file system

mountall [-k]

options

- 입력되는 데이타가 표준입력

-k 화일을 open시키고 프로세서를 찾은 다음 SIGKILL 시그널을 보낸다


95. mv, mvdir - 파일 이동이나, 이름 바꾸기

파일이름(rename) / 위치(move)변경


% mv index.htm index.html

: index.htm 화일을 index.html 로 이름 변경

$ mv file ../main/new_file

: 파일의 위치변경


96. nawk - 패턴 검색과 언어 처리


97. nice - 낮은 우선권에서 명령 실행

문법 nice [- number] command [arguments]

options

- number 우선 순위를 1에서 19까지로 지정하며 디폴터로는 10


98. nm - 심블 이름 목록 보기


99. nroff - 문서 포멧 도구


100. od - 8진수, 10진수, 16진수, ascii 덤프

8진수로 덤프하는 명령어

문법 od [-bcdox] [file] [[+[x]] offset [.] [b]]

options

-b 8진수로 byte를 해석

-c ASCII code로 byte를 해석

-d 10진수로 단어를 해석

-o 8진수로 단어를 해석

-x 16진수로 단어를 해석


101. passwd, chfn, chsh - 비밀번호, 핑거정보, 쉘 바꾸기


102. paste - 여러파일의 서로 관련 있는 줄 연결시키기


103. pr - 문서 파일 양식화 도구


104. printenv - 현재 환경 변수들의 내용과 그 값 알아보기


105. prof - profile 자료 보기


106. ps - 현재 프로세스 정보 보기

실행중인 프로세스에 관한 정보를 출력하는 명령어

문법 ps [options]

options

-a 프로세스 그룹의 리더 및 단말장치와 관계없는 프로세스를 제외한 빈번하게 사용되는 모든 프로세스에 관한 정보를 출력

-d 프로세스 그룹의 리더(rearder)를 제외한 모든 프로세스에 대한 정보를 출력

-e 현재 system내에서 실행중인 모든 프로세스 정보를 출력

-f 프로세스 관한 전부의 정보를 출력

-l 프로세스에 관한 정보를 long(롱)으로 출력

-n name list system 내의 name list 화일의 이름을 지정

-u uidlist 지정한 사용자 ID번호 또는 login명을 갖고있는 프로세스에 관한 정보만을 출력


107. ptx - permuted(순열화된?, 교환된?) 색인 만들기


108. pwd - 현재 작업 디렉토리 보기


109. quota - 한 사용자에게 지정된 디스크 할당량보기


110. ranlib - archive를 random 라이브러리로 변화


111. rcp - 리모트 카피


112. rcs - RCS 파일 속성 바꾸기


113. rcsdiff - RCS revisions 비교


114. rev - 한 줄의 문자열 꺼꾸로


115. rlogin - 리모트 로그인


116. rm, rmdir - 파일, 디렉토리 지우기

% rm test.html : test.html 화일 삭제

% rm -r <디렉토리> : 디렉토리 전체를 삭제

% rm -i a.*

: a로 시작하는 모든 파일을 일일이 삭제할 것인지 확인하면서 삭제


117. roffbib - 도서목록형 데이터베이스 보기 또는 양식화


118. rsh - 리모트 쉘


119. rup - 로칼 머쉰의 호스트 상태 보기(RPC version)


120. ruptime - 로칼 머쉰의 호스트 상태 보기


121. rusers - 현재 접속자 보기 (RPC version)


122. rwall - 모든 사용자에게 알림(RPC)


123. rwho - 현재 접속자 보기


124. sccs - Source Code Control System (SCCS)

125. sccs-admin, admin - SCCS 사용 내역 파일을 만들고, 관리


126. sccs-cdc, cdc - SCCS 델타의 델파 주석을 바꿈


127. sccs-comb, comb - SCCS 델타 조합


128. sccs-delta, delta - SCCS 파일에 데해 델타를 만듬


129. sccs-get, get - SCCS 파일 버전확인


130. sccs-help, help - SCCS 오류나 경고 메시지 검색


131. sccs-prs, prs - SCCS 사용내역의 선택된 부분 보기


132. sccs-prt, prt - SCCS 파일에서 델타 테이블 정보를 봄


133. sccs-rmdel, rmdel - SCCS 파일에서 델타를 지움


134. sccs-sact, sact - SCCS 파일의 편집 상태를 봄


135. sccs-sccsdiff, sccsdiff - SCCS 파일들의 버전 비교


136. sccs-unget, unget - SCCS 파일의 미리 얻은 것(?)을 취소한다.


137. sccs-val, val - SCCS 파일 유요화


138. script - 화면 갈무리


139. sdiff - 라인 단위의 차이를 비교하는 diff 명령어

문법 sdiff [losw] file1 file2

options

-r 라인 내용이 같으면 왼쪽만 출력

-o output 사용자가 지정한 문법으로 file1과 file2를 합병하고 같은 내용의 라

인을 output으로 지정한 화일에 복사

-s 같은 내용의 라인을 출력하지 않음

-Wn 인수 n 만큼 출력 라인의 폭을 지정


140. sed - stream editor

문법 sed [-efn] files

options

-e script 편집 명령어의 script를 지정

-n 이 옵션 생략시 출력하지 않음

-f sfile 화일 sfile에 script를 취하여 편집

-files 편집할 화일 지정

141. sh - 유닉스 표준 쉘


142. size - 오브젝트 파일의 크기들을 보여줌


143. sleep - 지정한 시간 만큼 실행 보류

초단위로 정의된 시간을 n 초 동안 실행을 정지시키는 명령어

문법 sleep time


144. sort - 줄 정열과 검색

모든 화일의 라인을 함께 소트(sort)하여 그 결과를 화면 또는 지정한 장소에 출력하는 명령어

문법 sort [-cmu]

[-o output]

[-ykmem]

[-zrecsz]

[-dfiMnr]

[-btx]

[+pos1 [pos2]] [files]

options

-b 필드비교시 앞에 붙는 공백을 무시

-c 입력화일이 순서대로 소트 되어있는지를 검사하여 소트되어 있지 않

으면 출력하지 않는다

-d 사전식 순서비교

-f 대문자와 소문자를 구별하지 않는다

-i 인쇄불가능 문자를 무시

문자비교에 있어 ASCII코드 040-0176의 문자만 유효

-r 역순으로 소트

-o output 출력화일명을 output으로 지정

-m 화일을 합병(merge)한다

-u 화일내의 같은 라인은 한 라인만 남기고 삭제


145. sortbib - 도서목록형 데이터베이스 정열


146. spell, hashmake, spellin, hashcheck - 맞춤범 검사(물론 영어겠지요)


147. split - 파일 나누기

system의 화일을 분할하는 명령어

문법 split [-n] [file [name]]

options

-n 화일을 n라인씩 분할하며 이 옵션을 생략하면 1000라인씩 분할


148. strings - 오브젝트 파일이나, 실행 파일에서 문자열 찾기


149. strip - 오브젝트 파일에서 심벌 테이블과 중복된 비트 삭제


150. stty - 터미날 설정

단말장치의 옵션의 설정상황을 출력한다

문법 stty [-a] [-g] [options]

options

-a 모든 옵션의 설정사항을 출력

-g 현재의 설정사항을 출력


151. su - super-user, 임시적으로 새 ID로 바꿈


152. sum - 화일 check sum과 블럭수를 나타내는 명령어

문법 sum [-r] file

options

-r 알고리즘을 check sum계산에 사용

file sum 처리를 하는 화일명


153. symorder - 심벌 순서 바꿈


154. tabs - 터미날 tab 크기 지정


155. tail - 파일의 끝 부분 보기

% tail -n filename : n줄 만큼 아래에서부터 보여줌


156. talk - 다른 사용자와 이야기하기


157. tar - 여러 파일 묶기 또는 묶긴 파일 풀기

.tar, _tar로 된 파일을 묶거나 풀때 사용하는 명령어

(압축파일이 아님)


% tar cvf [파일명(.tar, _tar)] 압축할 파일(또는 디렉토리): 묶을때

% tar xvf [파일명(.tar, _tar)] : 풀 때

(cf) cvfp/xvfp 로 하면 퍼미션 부동


아카이브 화일을 자기테이프에 저장하는 명령어

문법 tar [crtuxNbf lmgvw] [file ... ]

options

c 새로운 테이프에 새로 저장

r 지정한 화일을 테이프의 마지막부터 저장

t 지정한 화일이 테이프에 검출될 때마다 화일명 및 정보를 출력

x 지정한 화일을 테이프에서 꺼집어 낸다


158. tbl - nroff 또는 troff의 도표 작성 도구


159. tee - 표준 출력으로 방향 전환


160. telnet - TELNET 프로토콜을 이용한 원격 리모트 호스트 접속


161. test - 주워진 환경이 참인지, 거짓인지를 돌려줌


162. tftp - 간단한 ftp.


163. time - 명령 실행 시간 계산


164. touch - 파일 날짜 관련 부분을 바꿈

파일이나 디렉토리의 timestamp를 업데이트시키는 명령어이다. 현존하는 특정 파일을 지정하지 않으면, 해당 이름의 비어있는 파일이 생성된다


165. troff - 문서 양식화 도구


166. true, false - 쉘 스크립트에서 사용되는 참/거짓을 리턴하는 명령


167. tsort - topological sort


168. tty - 현재 터미날 이름 보기


169. ue - MICROemacs


170. ul - 밑줄 속성 문자 표현


171. umask - 시스템 파일이 만들어질 때 허가권의 기본값을 정하기 위해 사용되는 명령어


172. unifdef - cpp 입력 줄에서 ifdef 부분 바꾸거나 지움


173. uniq - 중복되는 빈줄 지우기

문법 uniq [-dcu [+n] [-n]] [input [output]]

options

-c 각 라인 앞의 중복된 횟수를 나타낸다

-d 중복된 라인의 첫째 라인만 출력

-u 중복되지 않은 라인만 출력

input 입력화일 지정

output 출력화일 지정


174. units - 프로그램 변환도구


175. uptime - 시스템 부팅 기간 보기


176. users - 현재 접속 사용자 보기


177. uucp, uulog, uuname - 시스템 간의 복사

178. uuencode, uudecode - 이진 파일을 아스키파일로 인코딩, 반대로 디코딩


179. uusend - 리모트 호스트에 파일 보내기


180. uux - 리모트 시스템 명령 실행


181. vacation - 자동으로 편지 답장하기


182. vgrind - grind nice program listings


183. vi, view, vedit - ex 바탕의 편집기


184. vtroff - 문서 양식화 도구


185. w - 현재 누가 접속해 있으며, 무엇을 하고있는지


186. wait - 프로세스가 마치기를 기다림

프로세스의 종료를 기다린 후 그 결과를 출력하는 명령어

문법 wait [n]

options

n 대기하는 백그라운드 프로세서 ID를 지정


187. wall - 모든 사용자에게 알림

UNIX sysytem을 사용하는 모든 사용자에게 메세지를 전달하는 명령어

문법 wall login name


188. wc - 단어, 줄, 바이트 계산

화일에 있는 단어 ,라인,문자수를 계산하는 명령어

문법 wc [-clw] [file ... ]

options

-c 문자수만 계산

-l 라인수만 계산

-w 단어수만 계산


189. what - 파일에서 SCCS 버전 정보 알아냄


190. whatis - 명령의 간단한 설명 보여줌


191. whereis - 찾는 명령의 실행파일, 소스, 맨페이지가 어디 있는지 경로를 보여줌


192. which - 명령만 찾음.


193. who - 시스템에 접속되어 있는 사람만 보여줌


194. whoami - 현재 사용하고 있는 자신이 누군지 보여줌


195. write - 다른 사용자의 화면에 특정 내용을 알림

다른 사용자에게 메세지를 전달하는 명령어

문법 write user [line]

options

user 메세지를 보내는 사용자명

line 접속할 라인이나 terminal을 지정


196. xargs - 명령행 인자 처리 명령


197. xstr - extract strings from C programs to implement shared strings


198. yacc - yet another compiler-compiler: 파싱(형태소분석) 프로그램 생성기


199. yes - 항상 yes만 응답하는 명령


200. zcat - 압축 파일 내용보기

'OS > 리눅스 & 유닉스' 카테고리의 다른 글

IBM nmon FAQ  (0) 2012.03.16
Unix Programming Frequently Asked Questions  (0) 2012.03.16
Using the "truss" command in Solaris  (0) 2012.03.16
Thread Functions for POSIX, Solaris and Windows NT  (0) 2012.03.14
sigwaitinfo  (0) 2012.02.21
:

Using the "truss" command in Solaris

OS/리눅스 & 유닉스 2012. 3. 16. 14:05

Using the "truss" command in Solaris

by Jeff Hunter, Sr. Database Administrator

Using truss

Truss is used to trace the system/library calls (not user calls) and signals made/received by a new or existing process. It sends the output to stderr.

NOTE: Trussing a process throttles that process to your display speed. Use -wall and -rall sparingly.
Truss usage

    truss  -a  -e  -f  -rall  -wall  -p  
    truss  -a  -e  -f  -rall  -wall  

    -a        Show arguments passed to the exec system calls
    -e        Show environment variables passed to the exec system calls
    -f        Show forked processes 
                (they will have a different pid: in column 1)
    -rall     Show all read data (default is 32 bytes)
    -wall     Show all written data (default is 32 bytes)
    -p        Hook to an existing process (must be owner or root)
    <program> Specify a program to run
  
Truss examples
  # truss -rall -wall -f -p <PID>
  # truss -rall -wall lsnrctl start
  # truss -aef lsnrctl dbsnmp_start
  
A Running Example (using the date command)
  # truss -d date

Base time stamp:  1066157908.5731  [ Tue Oct 14 14:58:28 EDT 2003 ]
 0.0000 execve("/usr/bin/date", 0xFFBEF29C, 0xFFBEF2A4)  argc = 1
 0.0449 mmap(0x00000000, 8192, PROT_READ|PROT_WRITE|PROT_EXEC,MAP_PRIVATE|MAP_ANON, -1, 0) = 0xFF3A0000
 0.0453 resolvepath("/usr/lib/ld.so.1", "/usr/lib/ld.so.1", 1023) = 16
 0.0457 open("/var/ld/ld.config", O_RDONLY)             Err#2 ENOENT
 0.0460 open("/usr/lib/libc.so.1", O_RDONLY)            = 3
 0.0463 fstat(3, 0xFFBEE9C4)                            = 0
 0.0464 mmap(0x00000000, 8192, PROT_READ|PROT_EXEC, MAP_PRIVATE, 3, 0) = 0xFF390000
 0.0466 mmap(0x00000000, 794624, PROT_READ|PROT_EXEC, MAP_PRIVATE, 3, 0) = 0xFF280000
 0.0470 mmap(0xFF33A000, 24652, PROT_READ|PROT_WRITE|PROT_EXEC,MAP_PRIVATE|MAP_FIXED, 3, 696320) = 0xFF33A000
 0.0474 munmap(0xFF32A000, 65536)                       = 0
 0.0479 memcntl(0xFF280000, 113332, MC_ADVISE, MADV_WILLNEED, 0, 0) = 0
 0.0481 close(3)                                        = 0
 0.0483 open("/usr/lib/libdl.so.1", O_RDONLY)           = 3
 0.0485 fstat(3, 0xFFBEE9C4)                            = 0
 0.0487 mmap(0xFF390000, 8192, PROT_READ|PROT_EXEC, MAP_PRIVATE|MAP_FIXED,3, 0) = 0xFF390000
 0.0490 close(3)                                        = 0
 0.0493 open("/usr/platform/SUNW,Ultra-5_10/lib/libc_psr.so.1", O_RDONLY) = 3
 0.0496 fstat(3, 0xFFBEE854)                            = 0
 0.0497 mmap(0x00000000, 8192, PROT_READ|PROT_EXEC, MAP_PRIVATE, 3, 0) = 0xFF380000
 0.0500 mmap(0x00000000, 16384, PROT_READ|PROT_EXEC, MAP_PRIVATE, 3, 0) = 0xFF370000
 0.0502 close(3)                                        = 0
 0.0514 munmap(0xFF380000, 8192)                        = 0
 0.0521 brk(0x00022420)                                 = 0
 0.0523 brk(0x00024420)                                 = 0
 0.0526 time()                                          = 1066157908
 0.0531 open("/usr/share/lib/zoneinfo/US/Eastern", O_RDONLY) = 3
 0.0533 read(3, " T Z i f\0\0\0\0\0\0\0\0".., 8192)     = 1250
 0.0536 close(3)                                        = 0
 0.0542 ioctl(1, TCGETA, 0xFFBEEFDC)                    = 0
Tue Oct 14 14:58:28 EDT 2003
 0.0545 write(1, " T u e   O c t   1 4   1".., 29)      = 29
 0.0547 llseek(0, 0, SEEK_CUR)                          = 1829
 0.0549 _exit(0)
NOTE: The "truss" command works on SUN and Sequent. Use "strace" on Linux. If your operating system doesn't support the truss and strace commands, call your system administrator to find the equivalent command on your system.

Monitor your Unix system:

Unix message files record all system problems like disk errors, swap errors, NFS problems, etc. Monitor the following files on your system to detect system problems:

  # tail -f /var/adm/SYSLOG
  # tail -f /var/adm/messages
  # tail -f /var/log/syslog
  

 http://www.idevelopment.info/data/Unix/Solaris/SOLARIS_UsingthetrussCommandinSolaris.shtml

'OS > 리눅스 & 유닉스' 카테고리의 다른 글

Unix Programming Frequently Asked Questions  (0) 2012.03.16
UNIX 명령어  (0) 2012.03.16
Thread Functions for POSIX, Solaris and Windows NT  (0) 2012.03.14
sigwaitinfo  (0) 2012.02.21
pthread_kill  (0) 2012.02.16
:

Thread Functions for POSIX, Solaris and Windows NT

OS/리눅스 & 유닉스 2012. 3. 14. 18:31

Thread Functions for POSIX, Solaris and Windows NT


This document describes some of the functions available for use with multithreaded applications underPOSIX , Solaris   and on Windows 9x/NT .

The POSIX thread functions are:

The POSIX semaphore functions are:

The Solaris (Sun)  thread functions are:

The 9x/NT thread functions are:

POSIX Threads

When compiling multithreaded programs, you must add the line
#include <pthread.h>
at the start of your program. In addition, you must link against the thread library. So, assuming you have a file named foo.c that you want to compile and that it uses the thread libraries, you compile it like this:
gcc -o foo foo.c -lpthread
for C++ programs
g++ -o foo foo.cpp -lpthread

pthread_create

Use the pthread_create function to create a new thread. The prototype is

#include <pthread.h>

int pthread_create(pthread_t *new_thread, const pthread_attr_t thread_attribute,
                void *(*start_routine)(void *), void *arg);
While this looks terribly confusing, you're basically specifying a function to execute within the new thread (the start_routineparameter is a function pointer) and the parameter to pass to that function (the argparameter). The function in which the thread starts should take one void* parameter and return void*.

The first parameter (new_thread) is a pointer to a variable of type pthread_t (basically a long integer) and will be filled in with the thread ID of the new thread.

The second parameter lets you specify how the thread's  should behave, but we'll just use NULL, which lets the operating system use the default values. (See the man page for the details of what else you can specify.) The thread_attribute  parameter lets you specify some details about the thread. Some valid values are: 
 

ValueMeaning
NULL Default attributes used

Below is an example that shows the function to run the thread (called ThreadFunc) and the code in main to start a new thread.

#include <pthread.h>

void* ThreadFunc( void* param )
{
    printf( "My thread ID is: %d\n", thr_self() );
}

void main( void )
{
    pthread_t threadID;
void *exit_status;

    pthread_create(&threadID, NULL, ThreadFunc, NULL);

    /* wait for the thread to finish */
    pthread_join( threadID,  &exit_status);
}
pthread_create returns 0 on success. Non-zero indicates an error. See the man page for details of error values.

pthread_join

The pthread_join function can be used by one thread to wait for another thread to finish. In this sense, it is like the wait system call that a process uses to wait for a child process to finish. The prototype is:

#include <pthread.h>

int pthread_join( pthread_t wait_for,
              void **status );
The wait_for parameter should be the ID of the thread you wish to wait for. If the value is 0, then pthread_join returns as soon as any(undetached) thread in the process terminates.. If statusis not NULL, then it will be filled in with the return value of the thread that terminated.

pthread_join returns 0 on success. Note that only one thread can successfully join any other thread. Subsequent calls to pthread_join for the terminated thread will return an error.


pthread_suspend and pthread_continue


The prototypes are

#include <pthread.h>

int pthread_suspend( pthread_t target_thread );
int pthread_continue( pthread_t target_thread );
Both calls take the ID of the thread to control as the only parameter. The call to pthread_suspend immediately suspends the execution of the threadspecified by target_thread. Calling pthread_continue allows a suspended thread to continue execution.

sched_yield

The prototype is

#include <pthread.h>

int sched_yield( );
The call to sched_yield immediately suspends the execution of the current thread. This allows another thread immediate access. At the next scheduling opportunity the thread resumes.

pthread_self

Some useful functions not covered in the examples:
sched_yield();         Informs the scheduler that the thread is willing to yield its quantum, requires
no arguments.

pthread_t me;
me = pthread_self(); Allows a pthread to obtain its own identifier


POSIX Thread Synchornization

Multi-threaded applications concurrently execute instructions. Access to process-wide (or interprocess) shared resources (memory, file descriptors, etc.) requires mechanisms for coordination or synchronization among threads. The pthread library offers synchronization primitives necessary to create a deterministic application. A multi-threaded application ensures determinism by forcing asynchronous thread contexts to synchronize, or serialize, access to data structures and resources managed and manipulated during run-time. These are mutual-exclusion ( mutex ) locks, condition variables, and read-write locks. The HP-UX operating system also provides POSIX semaphores (see next section).

Mutexes furnish the means to exclusively guard data structures from concurrent modification. Their protocol precludes more than one thread which has locked the mutex from changing the contents of the protected structure until the locker performs an analogous mutex unlock. A mutex can be initialized in two ways: by a call to pthread_mutex_init(); or by assignment of PTHREAD_MUTEX_INITIALIZER .

pthread_mutex_init

The pthread_mutex_init() function initializes the mutex referenced by mutex with the attributes attr. If the parameter attr is NULL, the default mutex attributes are used. Refer to pthread_mutexattr_init(3T) for a list of default mutex attributes. After successful initialization, the mutex is initialized, unlocked, and ready to be used in mutex operations. A mutex should be initialized only once or the resulting behavior is undefined. The pthread_once() function provides a way to ensure that a mutex is initialized only once. The macro PTHREAD_MUTEX_INITIALIZER can be used to initialize mutexes that are statically allocated. These mutexes will be initialized with default attributes. The pthread_mutex_init() function does not need to be called for statically initialized mutexes. The prototype is: 
#include <pthread.h>

pthread_mutex_t mutex;
int pthread_mutex_init( pthread_mutex_t *mutex,
const pthread_mutex_attr_t *attr );

Or,
#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

pthread_mutex_destroy

The pthread_mutex_destroy() function destroys the mutex referenced by mutex. This function may set mutex to an invalid value. The destroyed mutex can be reinitialized using the function pthread_mutex_init(). If the mutex is used after destruction in any mutex call, the resulting behavior is undefined. A mutex should be destroyed only when it is unlocked. Destroying a mutex that is currently being used results in undefined behavior. The prototype is: 
 int pthread_mutex_destroy(
pthread_mutex_t *mutex
);

pthread_mutex_lock

The mutex object mutex is locked by calling the pthread_mutex_lock() function. This operation returns with the mutex object referenced by mutex in the locked state with the calling thread as its owner. Deadlock detection is not provided. Attempting to relock the mutex causes deadlock. If a thread attempts to unlock a mutex that it has not locked or a mutex which is unlocked, undefined behavior results. Attempting to recursively lock the mutex results in undefined behavior. Attempting to unlock the mutex if it was not locked by the calling thread results in undefined behavior. Attempting to unlocked the mutex if it is not locked results in undefined behavior. The prototype is: 
#include <pthread.h>

int pthread_mutex_lock(
pthread_mutex_t *mutex
);

pthread_mutex_unlock

The function pthread_mutex_unlock() is called by the owner of the mutex referenced by mutex to unlock the mutex.  Undefined behavior will result ifpthread_mutex_unlock() is called on an unlocked mutex or by a thread that is not the current owner. If there are threads blocked on the mutex referenced by mutex when pthread_mutex_unlock() releases the mutex, the scheduling policy is used to determine which thread will acquire the mutex next. The prototype is:
#include <pthread.h>

int pthread_mutex_unlock(pthread_mutex_t *mutex);

POSIX Semaphores

sem_init

sem_init() is used to initialize an unnamed semaphore. A successful call to sem_init() will create a new unnamed semaphore referred to by sem to the non-negative value specified by value.  If pshared is equal to 0, the unnamed semaphore is not shared with other processes. If pshared is non-zero, the unnamed semaphore is sharable with any processes that can access semTo use this function, you must link in the realtime library by specifying -lrt on the compiler or linker command line. The prototype is:
#include <sys/semaphore.h>

int sem_init(sem_t *sem, int pshared, unsigned int value);
The following call to sem_init() will create a new unnamed semaphore referred to by sem, if one does not exist, initialize the unnamed semaphore descriptor, referred to by sem, to the non-negative value specified by value.
sem_t sem;
sem_init(sem, NULL, value);

sem_post

sem_post() is used to post the semaphore referenced by sem. The calling thread will not return from its call to sem_post() unless it can either: increment the semaphore value, if there are no blocked threads on this semaphore; give the semaphore to a blocked thread, if there are any blocked threads on this semaphore; or have an error condition. If the semaphore value is < 0, the semaphore has blocked threads, waiting for it to become available (the absolute value of the semaphore's value indicates the number of waiters at that moment). If the semaphore value is >= 0, the semaphore has no waiters. If the semaphore has no waiters at the time its value is checked, the semaphore's value will be atomically incremented, with respect to the checking of its value, up to its maximum value. If the semaphore has waiters at the time its value is checked, the semaphore value is not changed. Instead, the calling thread will attempt to wake up a waiter. The prototype is 
#include <sys/semaphore.h>
int sem_post(sem_t *sem);
The following call to sem_post() will post the semaphore sem.
sem_post(sem);

sem_wait

sem_wait() is used to lock a semaphore. The calling thread will not return from its call to sem_wait() until it successfully obtains a lock on the semaphore. The value of the semaphore sem is checked at some unspecified time during the call. If the semaphore is available at the time its value is checked, the calling thread will atomically, with respect to the checking of the value, lock the semaphore. The prototype is
#include <sys/semaphore.h>

int sem_wait(sem_t *sem);
The following call to sem_wait() will lock the semaphore sem .
sem_wait(sem);


Solaris or Sun UNIX

When compiling multithreaded programs, you must add the line
#include <thread.h>
at the start of your program. In addition, you must link against the thread library. So, assuming you have a file named foo.c that you want to compile and that it uses the thread libraries, you compile it like this:
gcc -o foo foo.c -lthread
for C++ programs
g++ -o foo foo.cpp -lthread

thr_create

Use the thr_create function to create a new thread. The prototype is

#include <thread.h>

int thr_create( void *stack_base, size_t stack_size,
                void *(*start_routine)(void *), void *arg,
                long flags, thread_t *new_thread );
While this looks terribly confusing, you're basically specifying a function to execute within the new thread (the start_routineparameter is a function pointer) and the parameter to pass to that function (the argparameter). The function in which the thread starts should take one void*parameter and return void* .

The first two parameters let you specify how the thread's stack should behave, but we'll just use NULL and 0 respectively, which lets the operating system use the default values. (See the man page for the details of what else you can specify.)

The last parameter (new_thread) is a pointer to a variable of type thread_t (basically a long integer) and will be filled in with the thread ID of the new thread.

The flags parameter lets you specify some details about the thread and its relationship to the process' LWPs. Some valid values are: 
 

ValueMeaning
0 No new LWP is added for this process
THR_NEW_LWP One new LWP is requested for the unbound threads
THR_BOUND One new LWP is requested to be bound to the thread being created. The new thread is a bound thread.
THR_SUSPENDED The new thread is created suspended and will not execute start_routine until it is started by thr_continue() .

You may combine values. Below is an example that shows the function to run the thread (called ThreadFunc) and the code in main to start a new thread.

#include <thread.h>

void* ThreadFunc( void* param )
{
    printf( "My thread ID is: %d\n", thr_self() );
}

void main( void )
{
    thread_t threadID;

    thr_create( NULL, 0, ThreadFunc, NULL, 
                THR_BOUND, &threadID );

    /* wait for the thread to finish */
    thr_join( threadID, NULL, NULL );
}
thr_create returns 0 on success. Non-zero indicates an error. See the man page for details of error values.

thr_join

The thr_join function can be used by one thread to wait for another thread to finish. In this sense, it is like the wait system call that a process uses to wait for a child process to finish. The prototype is:

#include <thread.h>

int thr_join( thread_t wait_for, thread_t *departed,
              void **status );
The wait_for parameter should be the ID of the thread you wish to wait for. If the value is 0, then thr_joinreturns as soon as any(undetached) thread in the process terminates. If departed is not NULL, then it is filled in with the ID of the thread that terminated. If statusis not NULL, then it will be filled in with the return value of the thread that terminated.

thr_join returns 0 on success. Note that only one thread can successfully join any other thread. Subsequent calls to thr_join for the terminated thread will return an error.


thr_suspend and thr_continue

The prototypes are

#include <thread.h>

int thr_suspend( thread_t target_thread );
int thr_continue( thread_t target_thread );
Both calls take the ID of the thread to control as the only parameter. The call to thr_suspend immediately suspends the execution of the thread specified bytarget_thread. Calling thr_continue allows a suspended thread to continue execution.

thr_yield

The prototype is

#include <thread.h>

int thr_yield( );
The call to thr_yield immediately suspends the execution of the current thread. This allows another thread immediate access. At the next scheduling opportunity the thread resumes.

Windows 9x/NT

In Windows 9x/NT when you write a multithreaded application, be sure to modify the project settings so that you link using the multithreaded library. If you're just compiling from the command line, then to compile a multithreaded program in the file foo.c, you would do this:
cl -MT foo.c
The -MT option tells the compiler to use the multithreaded library. If you're creating a project in Visual C++, create a console project. Once you've done that, add your source code file and then choose Settings from the Project menu. Then go to the C/C++ tab and choose Code Generation in the Category dropdown list. Then in the Use run-time library choose Multithreaded DLL for a release compile and Debug Multithreaded DLL for a debug compile.
CreateThread
 
Use the CreateThreadfunction to create a new thread. The prototype is
#include <windows.h>

HANDLE CreateThread( LPSECURITY_ATTRIBUTES lpThreadAttributes,
                     DWORD dwStackSize, 
                     LPTHREAD_START_ROUTINE lpStartAddress,
                     LPVOID lpParameter, DWORD dwCreationFlags,
                     LPDWORD lpThreadId );
While this looks even worse than the thr_createfunction, it is actually doing nearly the same things. First, a note about types in Windows 9x/NT. Anything prefixed with LPis simply a pointer to something. So LPSECURITY_ATTRIBUTES is simply a pointer to a structure of type SECURITY_ATTRIBUTES . ADWORD is a double word, that is, a 32-bit unsigned integer. Putting these together, we see that the LPDWORD is simply unsigned long* . Lastly, there's theHANDLEtype. This is basically void*, but is used in Windows simply as an identifier. Think of it as a number.

Now, on to the parameters. The first parameter is a pointer to a structure that determines whether the returned handle can be inherited by child processes. IflpThreadAttributes is NULL, the handle cannot be inherited. Security is not implemented on Windows 9x, so this parameter is ignored there. The second parameter (dwStackSize ) specifies the stack size for the new thread. A value of 0 gives it the same size as the calling thread (this is also what we did withthr_create ).

The next 2 parameters specify the address of the function (lpStartAddress) to execute in the thread and the parameter (lpParameter) to pass to it. The function prototype LPTHREAD_START_ROUTINE is equivalent to a function that looks like this:

DWORD WINAPI ThreadFunc( LPVOID );
So a thread routine in 9x/NT returns a DWORD, which is simply a long integer. WINAPI specifies a particular calling convention for the function. Be sure to include it when you write your routines. (For more details, search the Visual C++ online help for __stdcall, which is what WINAPIresolves to.) Note thatLPVOID(the parameter type) is simply void*, which is exactly what the thread routine in Solaris expects as well.

The last parameter (lpThreadId) takes a pointer to a variable of type DWORD (basically a long integer) and will be filled in with the thread ID of the new thread.

The dwCreationFlags parameter lets you specify some details about the thread and how it should run. Some valid values are: 
 

ValueMeaning
0 Use same settings as thread calling CreateThread .
THREAD_PRIORITY_LOWEST, 
THREAD_PRIORITY_BELOW_NORMAL, 
THREAD_PRIORITY_NORMAL, 
THREAD_PRIORITY_ABOVE_NORMAL, 
THREAD_PRIORITY_HIGHEST, 
THREAD_PRIORITY_IDLE, 
THREAD_PRIORITY_TIME_CRITICAL
These all specify thread priorities and are values that are added to the process' priority.
CREATE_SUSPENDED The new thread is created suspended and will not execute start_routine until it is started by ResumeThread() .

You may combine values. Below is an example that shows the function to run the thread (called ThreadFunc) and the code in main to start a new thread.

#include <windows.h>

DWORD WINAPI ThreadFunc( void* param )
{
    printf( "My thread ID is: %d\n", GetCurrentThreadId() );
}

void main( void )
{
    DWORD  threadId;
    HANDLE hThread;
    
    hThread = CreateThread( NULL, 0, ThreadFunc, NULL, 
                            0, &threadId );

    /* wait for the thread to finish */
    WaitForSingleObject( hThread, INFINITE );

    /* clean up resources used by thread */
    CloseHandle( hThread );
}
CreateThread returns NULL on failure. When successful, the return value is used to identify the thread and operate on it. Note that the thread ID is notused for this purpose in 9x/NT but isused this way in Solaris. The call to WaitForSingleObject is one of the synchronization functions in NT that we'll be discussing later. For now we'll just consider it the equivalent of Solaris' thr_join function. The CloseHandle call is used to remove the resources associated with anything identified via a HANDLE type (of which there are many in Windows programming).
WaitForSingleObject


The WaitForSingleObject function can be used by one thread to wait for another thread to finish (later we'll also see that this function is used for synchronization of other types as well). In this sense, it is like the wait system call that a process uses to wait for a child process to finish. The prototype is:

#include <windows.h>

DWORD WaitForSingleObject( HANDLE hThread,
                           DWORD dwMilliSeconds );
The hThread parameter should be the HANDLEof a thread as returned from CreateThread. The dwMilliSecondsparameter specifies in milliseconds how long you are willing to wait for the thread to finish. You may use the predefined value of INFINITE here if you like, which of course will cause the caller to block until the specified thread does terminate, regardless of how long that takes. If you specify a timeout less than INFINITE, then you need to check the return value to see why the call returned.

If the return value is WAIT_OBJECT_0, then the thread you were waiting on terminated. If the return is WAIT_TIMEOUT , then the timeout you specified elapsed before the thread finished. WAIT_FAILED is returned if the function failed for some reason.

See the section on CreateThread for an example of usage of WaitForSingleObject . There is also a WaitForMultipleObjects function which allows you to simultaneously wait until more than one object is in a signalled state. See the online help for usage.


SuspendThread and ResumeThread


The prototypes are

#include <windows.h>

DWORD SuspendThread( HANDLE hThread );
DWORD ResumeThread( HANDLE hThread );
Both calls take the HANDLEof the thread to control as the only parameter. The call to SuspendThread immediately suspends the execution of the thread specified by hThread. Calling ResumeThread allows a suspended thread to continue execution. Both functions return 0xFFFFFFFF on error and the thread's suspend count on success (see the online help in Visual C++ for an explanation of the suspend count).

'OS > 리눅스 & 유닉스' 카테고리의 다른 글

UNIX 명령어  (0) 2012.03.16
Using the "truss" command in Solaris  (0) 2012.03.16
sigwaitinfo  (0) 2012.02.21
pthread_kill  (0) 2012.02.16
grep 명령어  (0) 2012.02.13
:

sigwaitinfo

OS/리눅스 & 유닉스 2012. 2. 21. 09:21

1장. sigwaitinfo(2)

차례
1.1절. 사용법
1.2절. 설명
1.3절. 반환값
1.4절. 에러
1.5절. 예제
1.6절. 참고문헌

대기열의 시그널을 동기적으로 기다린다.


1.1절. 사용법

#include <signal.h>

int sigwaitinfo(const sigset_t *set, siginfo_t *info);
int sigtimedwait(const  sigset_t  *set,  siginfo_t  *info,
                 const struct timespec timeout);
		


1.2절. 설명

sigwaitinfo()는 시그널 셋set에 설정된 시그널중 하나가 전달될 때까지 대기한다. 설정된 시그널 중 하나가 전달되면 즉시 리턴한다. 만약 info가 NULL이 아니라면 시그널 관련 정보를 채워준다.

sigtimedwait()는 timeout만큼 신호를 기다리다가 신호가 없을 경우 리턴한다는 걸 제외하고는 sigwaitinfo()와 동일하다.

struct timespec 
{
    long    tv_sec;         /* seconds */
    long    tv_nsec;        /* nanoseconds */
}
		

다음은 info구조체에 정의된 멤버 변수들이다.

typedef struct siginfo {
   int si_signo;     /* Signal number */
   int si_errno;     /* Error code */
   int si_code;                                                    
   pid_t si_pid;
   uid_t si_uid;
   void *si_addr;
   union sigval si_value;
   union {                                                        
      /* Skipping other fields */
      struct {
         int _band;  /* Socket event flags (similar to poll) */   
         int _fd;    /* Socket fd where event occurred */          
      } _sigpoll;                                      
   } _sifields;                                        
}  siginfo_t;                                        
                                                          
#define si_fd     _sifields._sigpoll._fd                  
		


1.3절. 반환값

성공할 경우 sigwaitinfo(), sigtimedwait()모두 시그널 번호를 리턴한다. 실패했을 경우 -1을 리턴한다.


1.4절. 에러

EAGIN

sigtimedwait()에서 timeout동안 아무런 신호가 전달되지 않았을 ㅕㅇ우

EINVAL

timeout가 잘못 설정되었다.

EINTR

시그널 핸들러에 의해서 인터럽트가 걸렸다.


1.5절. 예제

#include <signal.h>
#include <stdio.h>
#include <unistd.h>

int main()
{
    struct sigaction sigact;
    siginfo_t info;
    int signo;
    printf("My pid %d\n", getpid());
    sigemptyset(&sigact.sa_mask);
    sigaddset(&sigact.sa_mask, SIGUSR2);
    while(1)
    {
        signo = sigwaitinfo(&sigact.sa_mask, &info);
        printf("%d : %d\n", signo, info.si_pid);
    }
}
		
위 프로그램은 SIGUSR2가 전달되는걸 기다린다. 만약 SIGUSR2 시그널을 받는다면 시그널을 전달한 프로세스의 PID를 출력한다.

아래 프로그램은 위의 예제를 테스트 하기 위한 프로그램이다. 인자로 SIGUSR2 시그널을 받을 PID를 지정한다. 시그널을 받은 프로그램 측에서 시그널을 보낸 프로세스의 PID를 얻어오는지 확인해 보도록 하자.

#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

int main(int argc, char **argv)
{
    int pid = atoi(argv[1]);
    printf("%d\n", getpid());
    while(1)
    {
        kill(pid, SIGUSR2);
        sleep(1);
        printf("OK SIG\n");
    }
}
		

'OS > 리눅스 & 유닉스' 카테고리의 다른 글

Using the "truss" command in Solaris  (0) 2012.03.16
Thread Functions for POSIX, Solaris and Windows NT  (0) 2012.03.14
pthread_kill  (0) 2012.02.16
grep 명령어  (0) 2012.02.13
grep, egrep, fgrep & 정규식  (0) 2012.02.13
:

pthread_kill

OS/리눅스 & 유닉스 2012. 2. 16. 08:44
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <errno.h>

void *t_function(void *data)
{
        char a[100000];
        int num = *((int *)data);
        struct timeval tm;


        pthread_detach(pthread_self());

        printf("Thread Start\n");

        tm.tv_sec = 3;
        tm.tv_usec = 0;
        select(0, NULL, NULL, NULL, &tm);

        printf("Thread end\n");
}

int main()
{
        pthread_t p_thread;
        int thr_id;
        int status;
        int a = 100;

        printf("Before Thread\n"); 
        thr_id = pthread_create(&p_thread, NULL, t_function, (void *)&a);
        if (thr_id < 0)
        {
                perror("thread create error : ");
                exit(0);
        }

        for ( ; ; ) {
                struct timeval tm;
                tm.tv_sec = 0;
                tm.tv_usec = 500000;
                select(0, NULL, NULL, NULL, &tm);

                status = pthread_kill(p_thread, 0);
                if ( status == ESRCH ) {
                        printf("Thread ID[%d] not exist..\n", p_thread);
                        return 0;
                } else if ( status == EINVAL ) {
                        printf("Thread ID[%d] is yet alive\n", p_thread);
                }  else {
                        printf("Thread ID[%d] is yet alive\n", p_thread);
                }
        }

        return 0;
}

pthread_kill

pthread_kill 은 대상 thread에게 signal을 전달하는 기능 수행

SYNTAX
int pthread_kill(pthread_t thread, int sig);

RETURN VALUE
성공 : 0
실패 : ERROR
ERRORS
ESRCH : thread ID로 해당 thread를 찾을 수 없는 경우
EINVAL : 잘못된 signal number를 전달할 경우

'OS > 리눅스 & 유닉스' 카테고리의 다른 글

Thread Functions for POSIX, Solaris and Windows NT  (0) 2012.03.14
sigwaitinfo  (0) 2012.02.21
grep 명령어  (0) 2012.02.13
grep, egrep, fgrep & 정규식  (0) 2012.02.13
shell 조건문  (0) 2012.02.11
:

grep 명령어

OS/리눅스 & 유닉스 2012. 2. 13. 21:36

1.grep 명령어


1.1 grep의 의미

grep : 파일 전체를 뒤져 정규표현식에 대응하는 모든 행들을 출력한다.

egrep : grep의 확장판으로, 추가 정규표현식 메타문자들을 지원한다.

fgrep : fixed grep 이나 fast grep으로 불리며, 모든 문자를 문자 그래도 취급한다. 즉, 정         규표현식의 메타문자도 일반 문자로 취급한다.


1.2 grep의 동작 방법

grep에서 사용하는 정규표현식 메타문자

메타문자

기    능

사용 예

사용 예 설명

^

행의 시작 지시자

'^love'

love로 시작하는 모든 행과 대응

$

행의 끝 지시자

'love$'

love로 끝나는 모든 행과 대응

.

하나의 문자와 대응

'l..e'

l 다음에 두 글자가 나오고 e로 끝나는 문자열을 포함하는 행과 대응

*

선행문자와 같은 문자의 0개 혹은 임의개수와 대응

' *love'

0개 혹은 임의 개수의 공백 문자 후에 love로 끝나는 문자열을 포함한 행과 대응

[]

[] 사이의 문자 집합중 하나와 대응

'[Ll]ove'

love나 Love를 포함하는 행과 대응

[^ ]

문자집합에 속하지 않는 한 문자와 대응

'[^A-K]love'

A와 K 사이의 범위에 포함되지 않는 한 문자와 ove가 붙어있는 문자열과 대응

\<

단어의 시작 지시자

'\

love로 시작하는 단어를 포함하는 행과 대응(vi,grep에서 지원)

\>

단어의 끝 지시자

'love\>'

love로 끝나는 단어를 포함하는 행과 대응

(vi,grep에서 지원)

\(..\)

다음 사용을 위해 태그를 붙인다.

'\(lov\)ing'

지정된 부분을 태크1에 저장한다. 나중에 태그값을 참고하려면 \1을 쓴다. 맨 왼쪽부터 시작해 태그를 9개가지 쓸 수 있다. 왼쪽 예에서는 lov가 레지스터1에 저장되고 나중에 \1로 참고할 수 있다.

x\{m\}

문자 x를 m번 반복한다.

'o\{5\}'

문자 o가 5회 연속적으로 나오는 모든 행과 대응

x\{m,\}

적어도 m번 반복한다.

'o\{5,\}'

문자 o가 최소한 5회 반복되는 모든 행과 대응

x\{m,n\}

m회 이상 n회 이하 반복한다.

o\{5,10\}'

문자 o가 5회에서 10회 사이의 횟수로 연속적으로 나타나는 문자열과 대응

grep의 옵션

옵션

동작 설명

-b

검색 결과의 각 행 앞에 검색된 위치의 블록 번호를 표시한다. 검색 내용이 디스크의 어디쯤 있는지 위치를 알아내는데 유용하다.

-c

검색 결과를 출력하는 대신, 찾아낸 행의 총수를 출력한다.  (count)

-h

파일 이름을 출력하지 않는다.

-i

대소문자를 구분 하지 않는다.(대문자와 소문자를 동일하게 취급). (ignore)

-l

패턴이 존재하는 파일의 이름만 출력한다.(개행문자로 구분) (list file)

-n

파일 내에서 행 번호를 함께 출력한다. (number)

-s

에러 메시지 외에는 출력하지 않는다. 종료상태를 검사할 때 유용하게 쓸 수 있다.

-v

패턴이 존재하지 않는 행만 출력한다. (invert)

-w

패턴 표현식을 하나의 단어로 취급하여 검색한다. (word)

# grep -n '^jack:' /etc/passwd

(/etc/passwd 파일에서 jack을 찾는다. jack이 행의 맨 앞에 있으면 행 번호를 화면으로 출력한다.)


1.3 grep과 종료 상태

grep은 파일 검색의 성공 여부를 종료 상태값으로 되돌려준다.

패턴을 찾으면 0, 패턴을 찾을 수 없으면 1, 팡리이 존재하지 않을 경우 2

sed,a자 등은 검색의 성공 여부에 대한 종료 상태값을 반환하지 않는다. 다만 구문 에러가 있을 경우에만 에러를 보고한다.


2. 정규표현식을 사용하는 grep의 예제

# grep NW datafile

# grep NW d*

(d로 시작하는 모든 파일에서 NW를 포함하는 모든 행을 찾는다.)

# grep '^n' datafile

(n으로 시작하는 모든 행을 출력한다.)

# grep '4$' datafile

(4로 끝나는 모든 행을 출력한다.)

# grep TB Savage datafile

(TB만 인자이고 Savage와 datafile은 파일 이름이다.)

# grep 'TB Savage' datafile

(TB Savage를 포함하는 모든 행을 출력한다.)

# grep '5\.' datafile

(숫자 5, 마침표, 임의의 한 문자가 순서대로 나타나는 문자열이 포함된 행을 출력한다.)

# grep '\.5' datafile

(.5가 나오는 모든 행을 출력한다.)

# grep '^[we]' datafile

(w나 e로 시작하는 모든 행을 출력한다.)

# grep '[^0-9]' datafile

(숫자가 아닌 문자를 하나라도 포함하는 모든 행을 출력한다.)

# grep '[A-Z][A-Z] [A-Z]' datafile

(대문자 2개와 공백 1개, 그리고 대문자 하나가 연이어 나오는 문자열이 포함된 행을 출력한다.)

# grep 'ss* ' datafile

(s가 한 번 나오고, 다시 s가 0번 또는 여러번 나온 후에 공백이 연이어 등장하는 문자열을 포함한 모든 행을 출력한다.)

# grep '[a-z]\{9\}' datafile

(소문자가 9번 이상 반복되는 문자열을 포함하는 모든 행을 출력한다.)

# grep '\(3\)\.[0-9].*\1 *\1' datafile

(숫자 3,마침표,임의의 한 숫자,임의 개수의 문자,숫자 3(태그),임의 개수의 탭 문자,숫자 3의 순서를 갖는 문자열이 포한된 모든 행을 출력한다.)

# grep '\<>

(north로 시작하는 단어가 포함된 모든 행을 출력한다.)

# grep '\' datafile

(north라는 단어가 포함된 모든 행을 출력한다.)

# grep '\<[a-z].*n\>' datafile

(소문자 하나로 시작하고, 이어서 임의 개수의 여러 문자가 나오며, n으로 끝나는 단어가 포함된 모든 행을 출력한다. 여기서 .*는 공백을 포함한 임의의 문자들을 의미한다.)


3. grep에 옵션 사용

# grep -n '^south' datafile

(행번호를 함께 출력한다.)

# grep -i 'pat' datafile

(대소문자를 구별하지 않게 한다.)

# grep -v 'Suan Chin' datafile

(문자열 Suan Chin이 포함되지 않은 모든 행을 출력하게 한다. 이 옵션은 입력 파일에서 특정 내용의 입력을 삭제하는데 쓰인다.

# grep -v 'Suan Chin' datafile >black

# mv black datafile

)

# grep -l 'SE' *

(패턴이 찾아진 파일의 행 번호 대신 단지 파일이름만 출력한다.)

# grep -w 'north' datafile

(패턴이 다른 단어의 일부가 아닌 하나의 단어가 되는 경우만 찾는다. northwest나 northeast 등의 단어가 아니라, north라는 단어가 포함된 행만 출력한다.)

# grep -i "$LOGNAME" datafile

(환 경변수인 LOGNAME의 값을 가진 모든 행을 출력한다. 변수가 큰따옴표로 둘러싸여 있는 경우, 쉘은 변수의 값으로 치환한다. 작은따옴표로 둘러싸여 있으면 변수 치환이 일어나지 않고 그냥 $LOGNAME 이라는 문자로 출력된다.)


4. egrep

egrep(extended grep) : grep에서 제공하지 않는 확장된 정규표현식 메타문자를 지원  한다.

                                    grep와 동일한 명령행 옵션을 지원한다.

egrep에서 지원하는 확장 메타문자

메타문자

기능

사용 예

사용 예 설명

+

선행문자와 같은 문자의 1개 혹은 임의 개수와 대응

'[a-z]+ove'

1개 이상의 소문자 뒤에 ove가 붙어있는 문자열과 대응. move,approve,love,behoove 등이 해당된다.

?

선행문자와 같은 문자의0개 혹은 1개와 대응

'lo?ve'

l 다음에 0개의 문자 혹은 하나의 문자가 o가 나오는 문자열과 대응. love,lve 등이 해당된다.

a|b

a 혹은 b와 대응

'love|hate'

love 혹은 hate와 대응.

()

정규표현식을 묶어준다

'love(able|ly)'

lovable 혹은 lovely와 대응.

'(ov)+'

ov가 한 번 이상 등장하는 문자열과 일치.


4.1 egrep 예제

# egrep 'NW|EA' datafile

(NW나 EA가 포함된 행을 출력한다.)

# egrep '3+' datafile

(숫자 3이 한 번 이상 등장하는 행을 출력한다.)

# egrep '2\.?[0-9]' datafile

(숫자 2 다음에 마침표가 없거나 한 번 나오고, 다시 숫자가 오는 행을 출력한다.)

# egrep ' (no)+' datafile

(패턴 no가 한 번 이상 연속해서 나오는 행을 출력한다.)

# egrep 'S(h|u)' datafile

(문자 S 다음에 h나 u가 나오는 행을 출력한다.)

# egrep 'Sh|u' datafile

(패턴 Sh나 u를 포함한 행을 출력한다.)

5. 고정 grep 과 빠른 grep

fgrep : grep 명령어와 동일하게 동작한다. 다만 정규표현식 메타문자들을 특별하게 취급하지

         않는다.

# fgrep '[A-Z]****[0-9]..$5.00' file

([A-Z]****[0-9]..$5.00 이 포함된 행을 출력한다. 모든 문자들을 문자 자체로만 취급한다.)

6. find 명령어

find 명령의 일반적인 형태는 다음과 같다.

find path expressions

각각의 인수들의 의미는 다음과 같다.

path

찾기 시작할 위치를 나타낸다. 예를들어, `.'은 현재 디렉토리를 나타내고, `/'은 루트 디렉토리부터 찾을 겻을 나타낸다.

expression

특정 파일을 찾기 위한 여려가지 조건들을 표현하는 부분으로 option, test, action, operator 등의 구문으로 구성되어진다.

그럼, expression의 각각의 구성 요소에 대하여 알아보자. option은 test와 상관 없이 항상 적용된다. option의 방법에는 다음과 같은 것이 있다.


-name : 확장자가 txt 인 화일을 찾는다.

         find / -name '*.txt'       

-perm : 퍼미션이 666(-rw-rw-rw-)인 화일을 찾는다.

         find . -perm 666       

-type : 파일의 타입을 지정하여, 찾고자하는 파일을 찾는다.

타입의 종류는 다음과 같다.
b : 블록 특수 파일(block device)
c : 캐릭터 특수 파일 (character deice)
d : 디렉토리(directory)
f : 일반파일(file)
l : 심볼릭 링크(link)
p : 파이프 (pipe)
s : 소켓 (socket)

현재 디렉토리 아래에 있는 서브디렉토리를 모두 찾는다.

         find . -type d       

-atime +n/-n/n : 최근 n일 이전에 액세스된 파일을 찾아준다.(accessed time)
+n은 n일 또는 그보다 더 오래 전의 파일
-n은 오늘 부터 n일 전까지의 파일
n은 정확히 n일 전에 액세스되었음을 의미한다.

시스템 전체에서 한 달 또는 그 이상의 기간동안 한번도 액세스하지 않은 디렉토리

         find / -atime +30 -type d       

-ctime +n/-n/n : ctime은 파일의 퍼미션을 마지막으로 변경시킨 날짜를 의미한다. (changed time)
+n은 n일 또는 그보다 더 오래 전의 파일
-n은 오늘 부터 n일 전까지의 파일
n은 정확히 n일 전에 수정되었음을 의미한다.

현재 디렉토리 아래에서 최근 일주일 동안 고친 파일

         find . -ctime -7       

-mtime +n/-n/n : mtime은 파일내의 data를 마지막으로 변경한 날짜를 의미한다.(modified time)
+n은 n일 또는 그보다 더 오래 전의 파일
-n은 오늘 부터 n일 전까지의 파일
n은 정확히 n일 전에 수정되었음을 의미한다.
-cnewer 파일명 : '파일명' 부분에 적어준 파일보다 더 최근에 수정된 파일들을 찾아준다.

test.txt 화일이 생성된 이후의 화일을 찾는다.

         find . -cnewer test.txt -print         

-user 유저네임 : '유저네임' 부분에 지정한 유저 소유의 파일을 찾아준다.

nalabi 라는 계정의 화일을 찾아준다.

         find / -user nalabi


그외 자주 쓰이지 않지만 추가 옵션으로는 아래와 같다.

-maxdepth n 
0이 아닌 정수값으로 경로 깊이를 지정하여 검색을 할 경우에 사용한다. 예를들어, '-maxdepth 1'은 시작위치로 지정한 디렉토리만 검색하고 하위 디렉토리는 찾지 않는다.

-mindepth 옵션은 반대로 동작한다. 즉, 지정한 숫자만큼의 깊이부터 그 하위 디렉토리를 검색한다. (GNU find 버전) 

-follow 
심볼릭 링크된 디렉토리도 검색을 할 경우에 사용한다.

-mount 
현재의 파일 시스템과 동일한 타입의 파일 시스템에서만 검색을 할 경우에 사용한다. 
test에는 다음과 같은 방법들이 있으며, test에 사용하는 인수에는 보다 큰 수를 의미하는 `'나, 보다 작은 수를 의미하는 `'를 함께 사용할 수 있다. 인수에 아무 연산자가 없을 경우에는 정확히 그 인수 값을 의미한다. 

-group 
특정 그룹 소유의 파일들을 찾을 경우에 사용한다. 

-nouser 
소유자가 없는 파일을 찾을 경우에 사용한다. 즉, /etc/passwd 파일에 없는 소유자의 파일을 찾을 경우에 사용한다. 

-nogroup 
올바른 그룹의 소유가 아닌 파일을 찾을 경우에 사용한다. 즉, /etc/groups 파일에 없는 그룹의 소유인 파일을 찾을 경우에 사용한다.

newer file1 file2
`file1' 보다는 이후에 `file2' 보다는 이전에 생성되거나 변형된 파일들을 찾을 경우에 사용한다.

-size n[bckw] 
크기가 
n 유닛(unit)인 파일을 찾을 경우에 사용한다. 유닛은 기본 설정(`b''와 함께 사용한 경우와 동일)인 512 바이트의 블럭, `c'를 사용할 경우에는 1 바이트, `k'를 사용할 경우에는 킬로바이트, `w'를 사용할 경우에는 2 바이트의 워드 크기를 나타낸다. 

-empty 
비어있는 파일이나 디렉토리를 찾을 경우에 사용한다. (GNU find 버전) 

-regex 
정규표현식(regular expression)을 이용하여 파일들을 찾을 경우에 사용한다. `
-iregex'는 대소문자를 구별하지 않을 경우에 사용한다. (GNU find 버전) 
action은 test에서의 조건과 일치하는 파일들에 대해 수행할 작업을 명시하는 것으로 다음과 같은 방법들이 있다. 

-print 
찾은 파일들을 표준출력(stdout)으로 출력한다. 기본으로 설정되어 있다. 

-fprint file 
찾은 파일들을 `
file'로 출력한다. `file'이 존재 하지 않을 경우에는 새로 생성되고, 존재할 경우에는 기존의 파일은 없어진다. (GNU find 버전) 

-exec 
파일을 찾았을 경우, 찾은 파일들에 대해 특정 명령을 수행 할 때 사용한다. 일반적으로 `-exec command {} ;'의 형식을 취한다. 

-ok 
-exec와 동일한 작업을 한다. 다른 점은, 명령을 실행할 때마다 실행 의사를 물어본다. 

-ls 
`ls -dils' 형식으로 찾은 파일들의 정보를 출력할때 사용한다. 

-fls file 
`
ls'와 동일하게 동작하며 결과를 `file'로 출력한다.
operator는 test에서 사용한 옵션들을 조합하여 조건식을 만들고자 할때 사용는 것으로 다음과 같은 방법들이 있다. (설명 순서는 우선순위(precedence)에 따른다.)

[예제] 
자신의 홈 디렉토리에서 확장자가 '.txt'인 파일을 찾을 경우 
$ find   -name "*.txt'' -print

현재 디렉토리 밑에서 첫글자가 영어 대문자인 모든 파일을 찾을 경우 
$ find . -name "[A-Z]*'' -print

'/usr/local'에서 첫 두글자는 영어 소문자이고 세번째 한자리는 숫자로 시작하는 이름을 가진 파일을 찾을 경우 
$ find /usr/local -name "[a-z][a-z][0-9]*'' -print

확장자가 .txt 인 파일을 찾으면서 현재 디렉토리와 한 단계 밑의 디렉토리에서만 파일을 찾을 경우 
$ find   -maxdepth 2 -name "*.txt'' -print

현재 디렉토리 밑에서 `zzang'이라는 이름을 가진 사용자 소유의 파일을 찾을 경우 
$ find . -user zzang -print

시스템에서 소유자나 그룹이 없는 파일을 찾을 경우 (크래커가 만들어 놓은 파일일 경우도 있음) 
$ find / -nouser -o -nogroup -print

자신의 홈 디렉토리에서 최근 3일 동안 변경된 파일들을 찾을 경우 
$ find . -mtime -3 -print

'/tmp'에서 최근 5일 동안 변경되지 않은 파일들을 찾아서 삭제할 경우 (파일을 삭제할 때마다 삭제할 것인가를 물어보도록) 
$ find . -mtime +5 -print -ok rm {} ;

현재 디렉토리 밑에 있는 모든 포스트 스크립트 파일(.ps)을 찾아서 gzip으로 압축을 하고 그 목록을 result.txt라는 파일에 저정할 경우 
$ find . -name "*.ps" -fprint result.txt -exec gzip {} ;

크랙커의 침입이 의심스러워 자신의 시스템에서 suid와 guid가 설정된 일반 파일들을 찾아서 권한을 확인할 경우 
$ find / -type f -perm +6000 -print -ls

시스템 관리의 실수로 일반 사용자가 쓰기 권한을 갖도록 설정되어 있는 파일을 찾아서 실행 권한을 없애는 경우 (단, 링크 파일은 제외함)
$ find / -perm +2 ! -type l -print -exec chmod o-w {} ;


7. 기타 활용

현재 디렉토리에서 가장 큰 파일을 찾기

$ find  .  -type  f  | xargs  du  -s  | sort  -n  |  tail  -1

위 한 줄의 명령어는 현재 디렉토리에 서브 디렉토리 포함하여 가장 큰 파일을 하나 찾아서 이를 출력하라는 의미이다.
간혹, 파일 시스템의 FULL이 되어서 가장 큰 파일을 찾으려고 할 경우 아주 유용하다.


*  현재 디렉토리에서 확장자가 cpp 이고 string 이란 문자열이 포함된 파일 검색

$ find / -name "*.cpp" -print -exec grep string {} \


*  현재 디렉토리 위치에서 하위디렉토리를 포함하여 string 이란 문자열을 포함한 파일 검색

$ find . -type f | xargs grep "string"

이 방법은 파일 이름에 공백이 들어갈 경우 문제가 생길 수 있습니다.
공백이 포함된 화일은 아래와 같이 찾아보시면 될거에요 
$ find . -type f -print0 | xargs -0 grep "string"

* 현재 디렉토리내에서 확장자가 cpp 이고 string 문자열을 포함하는 파일 검색


파일이름과 내용을 보여주려면..
$ grep string `find . -name \*\.cpp`

파일이름만 보여주려면..
$ grep -l string `find . -name \*\.cpp`


| (파이프, pipe, 수직바) 의 뜻은

"왼쪽 프로그램의 실행 결과를 오른쪽 프로그램의 입력으로 공급하라" 입니다.

파이프 왼쪽 오른쪽 프로그램이 동시에 실행된다는 것은 엄밀히 말하면 틀린얘기입니다.

왼쪽 프로그램이 실행되고 그 결과가 output 되면 오른쪽 프로그램의 input으로 공급되는 것입니다. 동시가 아닌 순차적인 개념입니다.

예를 들면, 

"검색 프로그램의 출력을 정렬 프로그램으로 파이프시킬 수 있고 다시 그 결과를 프린팅 프로그램으로 파이프시키거나 파일로 리다이렉트해서 저장할 수도 있다."


grep 은 가장 유용한 툴 중의 하나입니다.

grep 의 주된 기능은 정규표현식에 매칭되는 문자열을 찾아서 해당 라인만을 출력하는 것입니다.

쉽게 말해, 출력결과(or 입력)에서 찾는 문자열이 있는 라인만 보여주는 기능을 합니다.


egrep은 grep의 확장판인데 두개이상의 문자열을 검색합니다.

# netatte -ap | egrep "aaa|bbb|ccc"

하면  netstate의 결과물중 aaa 혹은 bbb 혹은 ccc가 있는 라인을 출력하는거죠

즉 or 검색이 가능합니다.


grep 하위 디렉토리 까지 조회시 -r 옵션 안될경우


보통 리눅스에서는 grep -r 하위 디렉토리까지 파일을 검색 할수 있게 recursive 옵션을 지원하지만 전통? grep에는 -r 옵션이 없는지 AIX ,HP,Solaris 에서는 -r 옵션을 사용 할수 없다.

그렇다면 여기서 find 와 xargs 를 이용하여 -r 옵션과 같은 실행을 할수 있는 방법은 아래와 같다.


ex) dir : /home/search/cgi-src

       1. -r 옵션 이용 : grep -r "include"  /home/search/cgi-src

       2.  find 와 xargs  이용 : find /home/search/cgi-src | xargs grep "include"


뭐 여기서 xargs는  간단하게 말해 파이프 '|' 를 통해 입력 받아서 xargs 뒤에 있는 명령어(grep)한테 파라미터를 주는것.


* xargs 활용 (여러파일 동시에 백업하기)


예를들어 test.cpp

            test1.cpp

            test2.cpp


이런식으로 다수의 파일이 있을떄 일일히 cp 명령어로 .bak 파일을 만드려면 번거로울 것이다.


한번에 처리할 수 있는 방법이 있다.

$ ls test* | xargs -t -i cp {} {}.bak

[출처] grep 명령 정규식|작성자 우유

'OS > 리눅스 & 유닉스' 카테고리의 다른 글

sigwaitinfo  (0) 2012.02.21
pthread_kill  (0) 2012.02.16
grep, egrep, fgrep & 정규식  (0) 2012.02.13
shell 조건문  (0) 2012.02.11
shell 조건 연산자  (0) 2012.02.11
:

grep, egrep, fgrep & 정규식

OS/리눅스 & 유닉스 2012. 2. 13. 21:34

grep, egrep, fgrep

1. 기능

파일에서 특정한 패턴(문자열)을 찾는 명령어이다. 이는 해당 문자열이 들어있는 파일을 찾아 그 문자열이 들어가 있는 라인(행)을 화면에 출력한다.

아래에 언급하는 메타문자를 활용하여 더욱 강력한 기능으로써 그 역할을 수행해낸다


2. 사용법

  (1)grep [옵션] [정규표현식(문자열)] [찾기 대상이 될 파일명]

-입력으로 파일명이 오지 않으면 표준입력으로부터 입력을 받는다

  (2)grep 패턴 *

-현재 디렉토리에서 해당 문자열이 들어있는 파일을 찾아서 그 문자열이 들어가 있는 라인(행)을 화면에 출력한다.(서브디렉토리까지 검색하기 위해서는 아래 옵션에 언급하는 바와 같이 -r옵션을 주어야 한다)

-grep 패턴 a* : a로 시작하는 모든 파일에서 해당 문자열이 들어있는 라인을 출력한다.

-이와 같이 간단하게 이용할 수도 있다.


3. 옵션

-옵션은 대소문자를 구분한다.

-c, --count : 파일의 내용 대신 문자열이 들어있는 라인의 수를 출력(3개의 라인에서 매칭된다면 3출력)

-n, --line-number : 문자열이 들어있는 라인과 문두에 라인번호를 출력

-i, --ignore-case : 문자열의 대소문자 구분하지 않음

-l(소문자 L), --files-with-matches : 문자열 을 포함하는 파일의 이름만 출력

-r, --recursive  : 서브 디렉토리의 파일까지 모두 출력

-v, --invert-match : 문자열이 제외된, 즉 문자열이 포함되어 있지 않은 라인을 출력

-e PATTERN, --regexp=PATTERN : pattern 에서 찾을 문자열 명시, 패턴으로 PATTERN을 사용("-으로 시작하는 패턴"을 보호하는데 유용)


-w, --word-regexp : pattern 이 전체 단어와 일치하는 줄만 출력, 단어의 일부로써 일치하는 경우가 아닌, 하나의 단어로써 일치하는 줄이 출력.

-x, --line-regexp : pattern 이 전체 줄과 일치하는 줄만 출력

-a, --text  : 기본적으로 grep는 바이너리 파일을 처리할 수없다. 그런데 바이너리파일을 텍스트파일처럼 처리할 수있는 옵션이 -a 옵션이다

-A NUM, --after-context=NUM : 패턴매칭라인 이후의 라인을 NUM수만큼 출력

-B NUM, --before-context=NUM : 패턴매칭라인 이전의 내용을 NUM수만큼 출력.

-C NUM, -NUM, --context=NUM : 출력물 앞뒤 전후의 주어진 라인만큼 출력(패턴매칭 라인은 포함하지 않고 기본 2라인)

-b, --byte-offset : 패턴매칭되기전 라인의 바이트수를 출력

--binary-files=TYPE :
파일 헤더가 바이너리를 포함한 파일을 가리키면 TYPE형 파일이라고 인식한다.
기본은 binary이다.
grep는 일반적으로 바이너리 파일을 알 수있는 하나의 메시지를 출력하거나 매치되지 않으면 메세지를 출력하지 않는다.
TYPE이 without-match 이면 grep는 바이너리파일이 매치되지 않는걸로 생각한다.
이는 -I(대문자 I) 옵션과 동등하다.
만약 TYPE이 text이면 grep은 텍스트파일로써 바이너리를 처리한다.
이는 -a 옵션과 동등하다.

-d ACTION, --directories=ACTION :
입력파일이 디렉토리이면 ACTION 처리한다.
기본적으로 ACTION은 read이고, 이는 원본파일인것처럼 디렉토리가 읽는다는것을 의미한다. ACTION이 skip이면 skip된다. ACTION이 recurse이면 grep은 각각의 디렉토리이하를 순환적으로 읽어들인다.
이는 -r 옵션과 동등하다.


(이하 옵션 다음 신지식 참고 : grep 사용법)
-E, --extended-regexp : 확장 정규표현식으로 패턴을 해석한다(=egrep 같은 의미)

-F, --fixed-strings : newline으로 분리된 고정된 문자열의 리스트로써 패턴을 해석한다(=fgrep과 같은 의미)

-f FILE, --file=FILE : 파일로부터 패턴을 얻는다(파일의 라인마다). 공백파일은 zero 패턴을 포함한다. 그러므로 매치되는것이 없다.

-G, --basic-regexp : 정규표현식으로써 PATTERN을 해석하고 이것이 기본이다

-H, --with-filename : 매칭되는 파일명을 출력

-h, --no-filename :여러개의 파일이 검색되었을때 -H 옵션처럼 앞에 파일명을 출력하지 않는다

--help : help 메세지를 출력

-I(대문자 i) : 매칭된 데이터를 포함하지 않는것처럼 바이너리 파일을 처리한다. binary-files=without-match 옵션과 동등하다

-i, --ignore-case : 주어진 패턴이나 입력파일에서 대소문자를 무시한다.

-L, --files-without-match : 일반적으로 출력되는 출력을 스킵하고 각각의 입력파일을 출력한다. 처음으로 매칭되는 파일이 나타나면 중지된다

-l, --files-with-matches : -L 과 반대

--mmap :
가능하면 read 시스템콜대신 입력을 읽어들이는 mmap 시스템콜을 사용한다.
이 경우, 보다나은 퍼포먼스를 유지하지만 또한, grep 작동중 입력파일이 줄어든다거나 I/O 에러가 발생하면 비정상적인 동작을 야기시키기도 한다

-q, --quiet, --silent : 출력을 억제한다. 처음으로 매칭되는것이 발견되면 중지한다. -s, --no-messages 옵션 참조

-r, --recursive : 하위 디렉토리를 순환적으로 모두 읽는다. -d recurse 옵션과 동등하다

-s, --no-messages :
존재하지 않거나 읽기불가능한 파일에대한 에러메세지을 출력하지 않는다.
GNU grep과는 다르게 정통 grep은 POSIX.2 규격에 부합하지 않는다. 때문에 정통 grep은 -q 옵션이나 GNU -q 옵션같은 -s 옵션의 역할이 미미하다.
쉘스크립트에선 이식성을 위해 정통 grep에서 -q, -s 옵션을 억제하거나 /dev/null로 리다이렉트 시킨다


-U, --binary :
바이너리 파일로 취급한다.
MS-DOS나 MS-Windows에서는 grep은 기본적으로 파일의 첫 32KB의 내용을 보고 파일타입을 예측한다.
만약 grep이 텍스트파일로 인식하면 (정확한 정규표현 작업을 위해서) 원본파일로부터 CR 문자를 없앤다.
-U 옵션에 쓰이는건 모든 파일이 읽혀지고 매칭절차를 지나쳐야 하기때문이다.
각 라인의 끝에 CR/LF 가 포함된 텍스트파일이라면 정규표현식 처리에 원하지 않는 결과가 발생할 것이다. 이 옵션은 MS-DOS, MS-Windows와 다른 플랫폼에서는 작동하지 않는다.

-u, --unix-byte-offsets :
유닉스 스타일의 바이트출력한다.
이런 변환이 있기때문에 grep이 유닉스 스타일의 텍스트파일처럼 읽기가 가능해진다.
이것은 유닉스머신에서의 grep처럼 정확한 결과를 산출할 것이다.
이 옵션은 -b 옵션이 쓰이지 않으면 소용이 없다.
MS-DOS, MS-Windows와 다른 플랫폼에서는 작동하지 않는다.  

-V, --version : 표준에러로 grep의 버전을 출력한다.

-w, --word-regexp :
문자열이 하나의 단어인 경우에만 검색, 즉 전체 단어유형 매칭을 포함하는 라인만 선택한다.
이 테스트는 매칭되는 문자열이 라인의 처음에 위치하거나 non-word에 의해 선두에 와야한다. 마찬가지로, 문미에 오거나 non-word가 마지막에 와야 한다.
word-constituent 는 문자,숫자,밑줄이 될 수있다.

-Z, --null :
파일명 대신 0 byte 문자를 출력한다.
예를들면, grep -IZ 는 유용한 newline 문자대신 각 파일명뒤에 0byte를 출력한다.
이 옵션은 newline과 같은 유용한 캐릭터를 포함하는 파일명까지도 출력을 명쾌하게 해준다. 이 옵션은 임의의 파일명을 처리하는 find -print0, perl -0, sort -z, xargs -0과 같은 명령어와 함께 사용될 수있고 newline 캐릭터를 포함하는 그 자체로도 사용할 수있다.


3. grep에서 사용하는 정규표현식 메타문자

메타문자
기    능
사용 예
사용 예 설명
^
행의 시작 지시자
'^love'
love로 시작하는 모든 행과 대응
$
행의 끝 지시자
'love$'
love로 끝나는 모든 행과 대응
.
하나의 문자와 대응
'l..e'
l 다음에 두 글자가 나오고 e로 끝나는 문자열을 포함하는 행과 대응
*
선행문자와 같은 문자의 0개 혹은 임의개수와 대응
*love'
0개 혹은 임의 개수의 공백 문자 후에 love로 끝나는 문자열을 포함한 행과 대응(*앞에 공백이 있는 상태, 다른 문자가 있다면 그 문자가 0개 혹은 임의 개수의 문자 후에 love로 끝나느 경우를 말함)
[]
[] 사이의 문자 집합중 하나와 대응
'[Ll]ove'
love나 Love를 포함하는 행과 대응
[^ ]
문자집합에 속하지 않는 한 문자와 대응
'[^A-K]love'
A와 K 사이의 범위에 포함되지 않는 한 문자와 ove가 붙어있는 문자열과 대응
\<
단어의 시작 지시자
'\<love'
love로 시작하는 단어를 포함하는 행과 대응(vi,grep에서 지원)
\>
단어의 끝 지시자
'love\>'
love로 끝나는 단어를 포함하는 행과 대응
(vi,grep에서 지원)
\(..\)
다음 사용을 위해 태그를 붙인다.
'\(lov\)ing'
지정된 부분을 태크1에 저장한다. 나중에 태그값을 참고하려면 \1을 쓴다. 맨 왼쪽부터 시작해 태그를 9개가지 쓸 수 있다. 왼쪽 예에서는 lov가 레지스터1에 저장되고 나중에 \1로 참고할 수 있다.
x\{m\}
문자 x를 m번 반복한다.
'o\{5\}'
문자 o가 5회 연속적으로 나오는 모든 행과 대응
x\{m,\}
적어도 m번 반복한다.
'o\{5,\}'
문자 o가 최소한 5회 반복되는 모든 행과 대응
x\{m,n\}
m회 이상 n회 이하 반복한다.
o\{5,10\}'
문자 o가 5회에서 10회 사이의 횟수로 연속적으로 나타나는 문자열과 대응

(표참조 : http://www.leopit.com/Leophp/board/lecture_board/view.php?id=61&board_mode=linux)


4. egrep

egrep은 grep의 확장판으로서 grep가 하나의 문자열을  찾는 것 과는 달리, 여러개의 문자열을 동시에 찾을 수 있고, grep에서 활용할 수 있는 메타문자 이외에 추가 정규표현식 메타문자를 지원한다.

  (1)egrep에서 사용하는 정규표현식 메타문자

+  : + 앞의 정규표현식이 1회 이상 나타남
? : ? 앞의 정규표현식이 0 또는 1회 나타남
|  : 문자열간의 OR연산자
() : 정규 표현식을 둘러 쌈


  (2)egrep 예제

 egrep 'NW|EA' datafile : (NW나 EA가 포함된 행을 출력한다. NW와 EA사이에 파이프( | ))
 egrep '3+' datafile : (숫자 3이 한 번 이상 등장하는 행을 출력한다.)
 egrep '2.?[0-9]' datafile : (숫자 2 다음에 마침표가 없거나 한 번 나오고, 다시 숫자가 오는 행을 출력한다.)
 egrep ' (no)+' datafile : (패턴 no가 한 번 이상 연속해서 나오는 행을 출력한다.)
 egrep 'S(h|u)' datafile : (문자 S 다음에 h나 u가 나오는 행을 출력한다.)
 egrep 'Sh|u' datafile  : (패턴 Sh나 u를 포함한 행을 출력한다.)


5. fgrep

fgrep는 문자열로만 검색을 한다. 문자열 부분에 위치한 모든 문자를 "문자로써"취급한다. 즉, 정규표현식의 메타문자도 일반문자로 취급한다. fgrep은 문자열로만 검색하기 때문에 검색속도가 빠르다는 장점이 있다.


6. 참고
  (1)정규 표현식에서 메타문자(& ! . * ? $ 및 \) 앞에 백슬래시(\)를 나타내면 grep으로 하여금 그것의 특수 의미를 무시하도록 한다.
  ex) grep ^\.      // 마침표로 시작되는 줄을 찾음
        grep '\$'     // "$" 문자가 포함된 줄을 찾음

  (2)패턴을 작성할 때 \(역슬래쉬)가 들어가는 경우(\<, \(..\), x\{m\} 이러한 표현식 등)나, 특수문자를 문자자체로 인식하게 하려 \을 사용하는 경우, 패턴에 있어서 파이프( | )를 이용하는 경우에는 패턴을 따옴표(")나 작은 따옴표(')로 감싸주어야 한다.

'OS > 리눅스 & 유닉스' 카테고리의 다른 글

pthread_kill  (0) 2012.02.16
grep 명령어  (0) 2012.02.13
shell 조건문  (0) 2012.02.11
shell 조건 연산자  (0) 2012.02.11
chmod suid  (0) 2012.02.11
: