컴퓨터특강 (unix system programming) apue (files & directories...
TRANSCRIPT
1
컴퓨터컴퓨터 특강특강 (UNIX System Programming)(UNIX System Programming)
APUE (Files & Directories)APUE (Files & Directories) [Ch. 4][Ch. 4]
20062006년년 봄학기봄학기
문양세문양세
강원대학교강원대학교 컴퓨터과학과컴퓨터과학과
Page 2UNIX System Programmingby Yang-Sae Moon
강의강의 목표목표 및및 내용내용
강의 목표
• 파일의 상태 및 구조를 이해한다.
• 파일 시스템 구현을 이해한다.
• 디렉토리 구조 및 구현을 이해한다.
강의 내용
• 파일 상태
• 파일 접근 허가권
• 파일 시스템 구현
• 링크 (link)
• 디렉토리
APUE (Files & Directories)
2
Page 3UNIX System Programmingby Yang-Sae Moon
stat() stat() –– 파일파일 상태상태 확인확인
역할: 주어진 파일에 대한 정보를 stat 구조체에 얻어 온다.
buf: stat 구조체에 대한 포인터 (정보를 가져올 장소)
lstat()은 Symbolic Link가 가리키는 파일이 아닌 Symbolic Link 자체에 대
한 정보를 얻는다.
리턴 값: 성공하면 0, 실패하면 -1
#include <sys/types.h>#include <sys/stat.h>int stat (const char *pathname, struct stat *buf );int fstat (int filedes, struct stat *buf );int lstat (const char *pathname, struct stat *buf );
APUE (Files & Directories)
Page 4UNIX System Programmingby Yang-Sae Moon
stat stat 구조체구조체 (1/2)(1/2)
<sys/stat.h>에 정의
APUE (Files & Directories)
struct stat {mode_t st_mode; /* file type & mode (permissions) */ino_t st_ino; /* i-node number (serial number) */dev_t st_dev; /* device number (filesystem) */dev_t st_rdev; /* device number for special files */nlink_t st_nlink; /* number of links */uid_t st_uid; /* user ID of owner */gid_t st_gid; /* group ID of owner */off_t st_size; /* size in bytes, for regular files */time_t st_atime; /* time of last access */time_t st_mtime; /* time of last modification */time_t st_ctime; /* time of last file status change */long st_blksize;/* best I/O block size */ long st_blocks; /* number of 512-byte blocks allocated */
};
3
Page 5UNIX System Programmingby Yang-Sae Moon
stat stat 구조체구조체 (2/2)(2/2)
st_atime: 마지막으로 파일의 데이터를 읽은 시각
st_mtime: 마지막으로 파일의 데이터를 수정한 시각
st_ctime: 파일의 내용이 아니고 이름/권한 같은 상태를 변경한 시각
st_blksize: 가장 효율적인 I/O 블럭 크기 (예: 8192 bytes)
st_blocks: 파일이 차지하고 있는 공간의 크기 (512 byte의 블록 수)
APUE (Files & Directories)
Page 6UNIX System Programmingby Yang-Sae Moon
파일파일 타입타입 (1/3)(1/3)
보통 파일 (Regular File)
• 데이터를 포함하고 있는 텍스트 또는 이진 파일
디렉토리 파일 (Directory File)
• 파일의 이름들과 파일 정보에 대한 포인터들을 포함
문자 특수 파일 (Character Special File)
• 시스템에 장착된 어떠 장치를 가리키는 파일
• 문자 단위로 데이터를 전송하는 장치 (c---------)
블록 특수 파일 (Block Special File)
• 시스템에 장착된 어떤 장치를 가리키는 파일
• 블럭 단위로 데이터를 전송하는 장치 (b---------)
APUE (Files & Directories)
4
Page 7UNIX System Programmingby Yang-Sae Moon
파일파일 타입타입 (2/3)(2/3)APUE (Files & Directories)
특수 파일 예제
Page 8UNIX System Programmingby Yang-Sae Moon
파일파일 타입타입 (3/3)(3/3)
FIFO
• 프로세스 간 통신에 사용되는 파일 (IPC Programming에서 사용됨)
• Named Pipe라고도 부름
소켓 (socket)
• 네트워크를 통한 프로세스 간 통신에 사용되는 파일
• Network Programming에서 사용하는 보편적인 방법
심볼릭 링크 (Symbolic link)
• 다른 파일을 가리키는 포인터 역할을 하는 파일 (Windows의 “바로가기”에 해당)
APUE (Files & Directories)
5
Page 9UNIX System Programmingby Yang-Sae Moon
파일파일 타입타입 검사검사 (1/2)(1/2)
파일 타입을 검사하는 매크로 함수
• stat.h 파일(/usr/include/sys/stat.h)에 정의되어 있음
• S_ISREG() : 정규 파일
• S_ISDIR() : 디렉토리 파일
• S_ISCHR() : 문자 특수 파일
• S_ISBLK() : 블록 특수 파일
• S_ISFIFO() : pipe 또는 FIFO
• S_ISLNK() : 심볼릭 링크
• S_ISSOCK() : 소켓
해당 종류의 파일이면 1, 아니면 0을 리턴
stat 구조체의 st_mode 값을 검사함
APUE (Files & Directories)
type special permission
4 bits 3 bits 9 bits
st_mode
Page 10UNIX System Programmingby Yang-Sae Moon
파일파일 타입타입 검사검사 (2/2)(2/2)
파일 타입 상수
• stat.h 파일(/usr/include/sys/stat.h)에 정의되어 있음
• S_IFREG : 정규 파일
• S_IFDIR : 디렉토리 파일
• S_IFCHR : 문자 특수 파일
• S_IFBLK : 블록 특수 파일
• S_IFFIFO : pipe 또는 FIFO
• S_IFLNK : 심볼릭 링크
• S_IFSOCK : 소켓
S_ISxxx() 매크로 함수는 S_IFxxx 상수 값의 설정 여부를 판단
APUE (Files & Directories)
6
Page 11UNIX System Programmingby Yang-Sae Moon
예제예제: : stat.cstat.c (1/2)(1/2)
#include <sys/types.h> /* stat.c */#include <sys/stat.h>int main(int argc, char *argv[]){int i;struct stat buf;char *ptr;for (i = 1; i < argc; i++) {printf("%s: ", argv[i]);if (lstat(argv[i], &buf) < 0) {perror("lstat()"); continue;
}if (S_ISREG(buf.st_mode)) ptr = "regular";else if (S_ISDIR(buf.st_mode)) ptr = "directory";else if (S_ISCHR(buf.st_mode)) ptr = "character special";else if (S_ISBLK(buf.st_mode)) ptr = "block special";else if (S_ISFIFO(buf.st_mode)) ptr = "fifo";else if (S_ISLNK(buf.st_mode)) ptr = "symbolic link";else if (S_ISSOCK(buf.st_mode)) ptr = "socket";else ptr = "** unknown mode **";printf("%s\n", ptr);
}exit(0);
}
APUE (Files & Directories)
Page 12UNIX System Programmingby Yang-Sae Moon
예제예제: : stat.cstat.c (2/2)(2/2)
실행 결과
$ a.out /etc /dev/ttya /bin a.out/etc: directory/dev/ttya: symbolic link/bin: symbolic linka.out: regular
Symbolic Link 에 대한 정보도 얻기 위해서 stat() 대신 lstat()을 사용
APUE (Files & Directories)
7
Page 13UNIX System Programmingby Yang-Sae Moon
파일파일 허가권허가권 (File Permissions)(File Permissions)
File access permission bits (stat 구조체의 st_mode 값)
APUE (Files & Directories)
type special permission
4 bits 3 bits 9 bits
st_mode
other-execute
other-write
other-read
group-execute
group-write
group-read
user-execute
user-write
user-read
Meaning
0001S_IXOTH
0002S_IWOTH
0004S_IROTH
0010S_IXGRP
0020S_IWGRP
0040S_IRGRP
0100S_IXUSR
0200S_IWUSR
0400S_IRUSR
Octal Codest_mode mask
Page 14UNIX System Programmingby Yang-Sae Moon
관련관련 명령어명령어
UNIX 명령어 chmod
• File Access Permission 설정
• stat 구조체의 st_mode 값을 변경
UNIX 명령어 chown
• File 소유 User ID 설정
• stat 구조체의 st_uid 값을 변경
UNIX 명령어 chgrp
• File 소유 Group ID 설정
• stat 구조체의 st_gid
APUE (Files & Directories)
8
Page 15UNIX System Programmingby Yang-Sae Moon
허가권허가권 (Permissions) (1/2)(Permissions) (1/2)
Read 권한이 있어야
• O_RDONLY, O_RDWR를 사용하여 파일을 열 수 있다.
Write 권한이 있어야
• O_WRONLY, O_RDWR, O_TRUNC를 사용하여 파일을 열 수 있다.
디렉토리에 write 권한과 execute 권한이 있어야
• 해당 디렉토리에 파일을 생성할 수 있고,
• 그 디렉토리의 파일을 삭제할 수 있다
APUE (Files & Directories)
Page 16UNIX System Programmingby Yang-Sae Moon
허가권허가권 (Permissions) (2/2)(Permissions) (2/2)
파일이 포함된 모든 상위 디렉토리에 대해 execute 권한이 있어야 그 파
일을 열 수 있다.
디렉토리에 대한 read 권한이 있어야 디렉토리 안에 들어 있는 파일 이
름 목록을 읽을 수 있다.
디렉토리에 대한 write 권한이 있어야 디렉토리에 파일을 생성 삭제 할
수 있다.
디렉토리에 대한 execute 권한이 있어야 그 디렉토리나 그 하위 디렉토리
에 있는 파일을 열 수 있다.
APUE (Files & Directories)
9
Page 17UNIX System Programmingby Yang-Sae Moon
Effective User IDEffective User ID
Real User ID와 Real Group ID
• 실제 사용자 ID와 그 사용자가 속한 그룹 ID
• 로그인한 사용자 ID
• 일반적으로, Shell 상에서 작업을 수행할 때의 User 및 Group ID로 이해할 수 있음
Effective User ID와 Effective Group ID
• 프로세스의 속성
• 대부분의 경우 Real User ID 와 Real Group ID 가 사용되나, 다음에 설명하는 S_ISUID와
S_ISGID 비트가 Set된 경우에는 다르게 동작함
• 일반적으로, 프로세스가 수행될 때의 User ID 및 Group ID로 이해할 수 있음
APUE (Files & Directories)
Page 18UNIX System Programmingby Yang-Sae Moon
S_ISUIDS_ISUID와와 S_ISGID (1/2)S_ISGID (1/2)
stat 구조체의 st_mode의 비트로 표현됨
• S_ISUID : set-user-ID
• S_ISGID : set-group-ID
st_mode의 S_ISUID 비트가 설정된 실행 파일을 실행한 경우
• 그 실행 파일이 실행된 프로세스의 Effective User ID는
• Real User ID가 아니고,
• 그 실행 파일 소유자의 User ID가 된다.
st_mode의 S_ISGID 비트가 설정된 실행 파일을 실행한 경우
• 그 실행 파일이 실행된 프로세스의 Effective Group ID는
• Real Group ID가 아니고,
• 그 실행 파일 소유자의 group ID가 된다.
APUE (Files & Directories)
type special permission
4 bits 3 bits 9 bits
st_mode
10
Page 19UNIX System Programmingby Yang-Sae Moon
S_ISUIDS_ISUID와와 S_ISGID (2/2)S_ISGID (2/2)
S_ISUID, S_ISGID 모두가 설정된 실행 파일을 실행하는 경우
• Real User ID, Real Group ID 의 권한이 아니고,
• 그 파일 소유 User ID, Group ID 의 권한으로 실행됨
예제)$ ls -al /bin/passwd-r-sr-sr-x 1 root sys 23500 Jul 30 2003 /bin/passwd*
APUE (Files & Directories)
Page 20UNIX System Programmingby Yang-Sae Moon
access()access()APUE (Files & Directories)
Real User ID와 Real Group ID로 파일의 허가권 검사
리턴 값: 성공하면 0, 실패하면 -1
mode 값
#include <unistd.h>
int access (const char *pathname, int mode );
test for existence of tileF_OK
test for execute permissionX_OK
test for write permissionW_OK
test for read permissionR_OK
Descriptionmode
11
Page 21UNIX System Programmingby Yang-Sae Moon
예제예제: access(): access()
#include <sys/types.h> // access.c#include <fcntl.h>#include <unistd.h>
int main(int argc, char *argv[]){if (argc != 2) {printf("usage: a.out <pathname>\n");exit(-1);
}
if (access(argv[1], R_OK) < 0)perror("R_OK");
elseprintf("read access OK\n");
if (open(argv[1], O_RDONLY) < 0)perror("O_RDONLY");
elseprintf("open for reading OK\n");
return 0;}
APUE (Files & Directories)
Page 22UNIX System Programmingby Yang-Sae Moon
chmodchmod(), (), fchmodfchmod()()APUE (Files & Directories)
파일에 대해 Access Permission을 변경한다
• stat 구조체의 st_mode 변경
리턴 값: 성공하면 0, 실패하면 -1
mode : bitwise OR
• S_ISUID, S_ISGID, S_ISVTX
• S_IRUSR, S_IWUSR, S_IXUSR
• S_IRGRP, S_IWGRP, S_IXGRP
• S_IROTH, S_IWOTH, S_IXOTH
#include <sys/stat.h>#include <sys/types.h>int chmod (const char *pathname, mode_t mode );int fchmod (int filedes, mode_t mode );
12
Page 23UNIX System Programmingby Yang-Sae Moon
예제예제: : chmodchmod() (1/2)() (1/2)
#include <sys/types.h> // nchmod.c#include <sys/stat.h>
int main(){struct stat statbuf;
/* turn on both set-group-ID and group-execute */if (stat("foo", &statbuf) < 0)perror("stat(foo)");
if (chmod("foo", (statbuf.st_mode | S_IXGRP | S_ISGID)) < 0)perror("chmod(foo)");
/* set absolute mode to "rw-r--r--" */if (chmod("bar", S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) < 0)perror("chmod(bar)");
return 0;}
APUE (Files & Directories)
Page 24UNIX System Programmingby Yang-Sae Moon
예제예제: : chmodchmod() (2/2)() (2/2)APUE (Files & Directories)
실행 결과
13
Page 25UNIX System Programmingby Yang-Sae Moon
chownchown()()APUE (Files & Directories)
파일의 User ID와 Group ID를 변경한다.
• stat 구조체의 st_uid, st_gid 변경
리턴 값: 성공하면 0, 실패하면 -1
lchown()은 심볼릭 링크 자체를 변경한다.
UNIX 종류 및 버전에 따라 차이가 있을 수 있다.
• BSD 기반 시스템에서는 super-user만 변환 가능
• System V 계열 시스템은 일반 사용자도 변경 가능
#include <sys/types.h>#include <unistd.h>int chown (const char *pathname, uid_t owner, gid_t group );int fchown (int filedes, uid_t owner, gid_t group );int lchown (const char *pathname, uid_t owner, gid_t group );
Page 26UNIX System Programmingby Yang-Sae Moon
truncate(), truncate(), ftruncateftruncate()()APUE (Files & Directories)
파일의 크기를 주어진 length로 줄인다.
리턴 값: 성공하면 0, 실패하면 -1
#include <sys/types.h>#include <unistd.h>
int truncate (const char *pathname, off_t length );int ftruncate (int filedes, off_t length );
14
Page 27UNIX System Programmingby Yang-Sae Moon
강의강의 목표목표 및및 내용내용
강의 목표
• 파일의 상태 및 구조를 이해한다.
• 파일 시스템 구현을 이해한다.
• 디렉토리 구조 및 구현을 이해한다.
강의 내용
• 파일 상태
• 파일 접근 허가권
• 파일 시스템 구현
• 링크 (link)
• 디렉토리
APUE (Files & Directories)
Page 28UNIX System Programmingby Yang-Sae Moon
Block I/OBlock I/O
I/O is always done in terms of blocks.
Sequence of a read() system call
APUE (Files & Directories)
read() system call
the device driver(software in kernel)
the disk controller (hardware)
I/O request
trap n bytes
one block at a timeinterrupt
15
Page 29UNIX System Programmingby Yang-Sae Moon
InodeInode (Index Node)(Index Node)
한 파일은 하나의 i-node를 갖는다.
파일에 대한 정보를 가지고 있다.
• file size
• file permissions
• the owner and group ids
• the last modification and last access times
• if it's a regular or directory, the location of data blocks
• if it's a special file, device numbers
• if it's a symbolic link, the value of the symbolic link
stat 구조체의 필드는 i-node 에서 읽어온다.
APUE (Files & Directories)
Page 30UNIX System Programmingby Yang-Sae Moon
The Block Map (1/2)The Block Map (1/2)
Direct block pointers
• 10 direct block pointers
Indirect block pointer
• an indirect block to address 1024 blocks
Double indirect block pointer
• an double indirect block to contain 1024 indirect block pointers
How many blocks can be addressed?
You may meet this question in the final exam.
APUE (Files & Directories)
16
Page 31UNIX System Programmingby Yang-Sae Moon
The Block Map (2/2)The Block Map (2/2)APUE (Files & Directories)
Direct
block
pointers
Indirect
pointers
Double
indirect
pointers
. . .to blocks
0 .. 9
To blocks 10 .. 1033 (1024 blocks)
To blocks 1034 .. 2057
Locates up to 1000 indirects
Inode Disk blocks
Page 32UNIX System Programmingby Yang-Sae Moon
File System Layout (1/3)File System Layout (1/3)
Boot Block
• Boot code that is used when UNIX is first activated.
Super Block (information about the entire file system)
• the total number of blocks in the file system
• the number of inodes in the inode free list
• a bit map of free blocks
• the size of block in bytes
• the number of free blocks
• the number of used blocks
APUE (Files & Directories)
17
Page 33UNIX System Programmingby Yang-Sae Moon
File System Layout (2/3)File System Layout (2/3)
i-list (다음 페이지 참조)
• all the inodes associated with the files on the disk
• each block in the inode list can hold about 40 inodes
User Blocks
• for storing file blocks
Bad Blocks
• Several block that cannot be used
APUE (Files & Directories)
Page 34UNIX System Programmingby Yang-Sae Moon
File System Layout (3/3)File System Layout (3/3)APUE (Files & Directories)
. . .
Boot block
Super block
i-list
User block
User block
User block
User blocks
. . .
Inodes 1..40
Inodes 41..80
0
1
2
3
200
201
18
Page 35UNIX System Programmingby Yang-Sae Moon
강의강의 목표목표 및및 내용내용
강의 목표
• 파일의 상태 및 구조를 이해한다.
• 파일 시스템 구현을 이해한다.
• 디렉토리 구조 및 구현을 이해한다.
강의 내용
• 파일 상태
• 파일 접근 허가권
• 파일 시스템 구현
• 링크 (link)
• 디렉토리
APUE (Files & Directories)
Page 36UNIX System Programmingby Yang-Sae Moon
unlink()unlink()APUE (Files & Directories)
파일을 삭제하는 역할을 수행함
(엄밀히 말해서, 파일의 link count를 감소시킴)
• stat 구조체의 st_mode 변경
리턴 값: 성공하면 0, 실패하면 -1
파일이 삭제될 경우, inode와 data block이 삭제(free)된다.
#include <unistd.h>
int unlink (const char *pathname);
19
Page 37UNIX System Programmingby Yang-Sae Moon
예제예제: unlink() (1/2): unlink() (1/2)
#include <sys/types.h> // unlink.c#include <sys/stat.h>#include <fcntl.h>#include <unistd.h>
int main() {int fd, len;char buf[20];fd = open("tempfile", O_RDWR | O_CREAT | O_TRUNC, 0666);if (fd == -1) perror("open1");close(fd);
system("ls -l");
unlink("tempfile");
system("ls -l");
return 0;}
APUE (Files & Directories)
Page 38UNIX System Programmingby Yang-Sae Moon
예제예제: unlink() (2/2): unlink() (2/2)APUE (Files & Directories)
실행 결과
20
Page 39UNIX System Programmingby Yang-Sae Moon
symlinksymlink() () -- Symbolic Link Symbolic Link
Symbolic Link는 파일에 대한 간접적인 포인터임
• 실제 파일에 대한 “경로”를 저장하고 있는 파일임
APUE (Files & Directories)
#include <unistd.h>
int symlink (const char *actualpath, const char *sympath );
Symbolic Link를 만든다.
• Symbolic Link File의 내용은 actualpath에 해당함
• Symbolic Link File의 크기는 actualpath 문자열의 길이 (즉, 저장되는 내용이 문자열)
리턴 값: 성공하면 0, 실패하면 -1
파라미터 설명
• actualpath: 실제 파일
• sympath: 만들 Symbolic Link의 이름
Page 40UNIX System Programmingby Yang-Sae Moon
파일파일 관련관련 시간시간
stat 구조체의 st_atime
• 파일의 데이터가 마지막으로 읽혔던(read 되었던) 시간
• 즉, 마지막으로 read()가 호출된 시간
stat 구조체의 st_mtime
• 파일의 데이터가 마지막으로 변경(write)된 시간
• 즉, 마지막으로 write()가 호출된 시간
stat 구조체의 st_ctime
• 파일의 stat 구조체의 내용이 마지막으로 변경된 시간
• chmod(), chown() 등이 호출된 시간
APUE (Files & Directories)
21
Page 41UNIX System Programmingby Yang-Sae Moon
utimeutime()()APUE (Files & Directories)
파일의 최종 접근 시간과 최종 변경 시간을 조정한다.
times가 NULL 이면, 현재시간으로 설정된다.
리턴 값: 성공하면 0, 실패하면 -1
UNIX 명령어 touch 참고
#include <sys/types.h>#include <utime.h>int utime (const char *pathname, const struct utimbuf *times );
struct utimbuf {time_t actime; /* access time */time_t modtime; /* modification time */
}
각 필드는 1970-1-1 00:00 부터 현재까지의 경과 시간을 초로 환산한 값
Page 42UNIX System Programmingby Yang-Sae Moon
디렉토리디렉토리 (Directory)(Directory)
디렉토리 파일
• 일종의 파일이므로 open, read, close 함수 등을 사용할 수 있다.
• 디렉토리 파일 사용에 편리한 새로운 함수들도 제공된다.
디렉토리 파일의 내용은 구조체 dirent의 배열 형태로 저장됨
• file name: 파일 이름, 하위 디렉토리 이름, “.”, “..”
• i-node number
APUE (Files & Directories)
#include <dirent.h> struct dirent {
ino_t d_ino; /* i-node number */char d_name[NAME_MAX + 1]; /* filename */
}
22
Page 43UNIX System Programmingby Yang-Sae Moon
디렉토리디렉토리 접근접근 ((opendiropendir(), (), readdirreaddir())())APUE (Files & Directories)
opendir()로 디렉토리 파일을 열고,
readdir()로 디렉토리 파일의 내용을 읽는다.
• 읽을 때마다 디렉토리 파일의 current file offset은 읽은 구조체 dirent의 크기 만큼 증가
한다.
• 디렉토리의 항목 읽기 위해서는 해당 디렉토리에 대한 읽기 권한이 있어야 한다.
• 그러나, 쓰기권한이 있어도 write 함수로 직접 쓸 수는 없으며,
mkdir(), rmdir() 함수를 사용해야 한다.
리턴 값: 성공하면 구조체 주소, 실패하면 NULL
#include <sys/types.h>#include <dirent.h>DIR *opendir (const char *pathname);struct dirent *readdir(DIR *dp);
Page 44UNIX System Programmingby Yang-Sae Moon
rewinddirrewinddir(), (), closedirclosedir()()APUE (Files & Directories)
rewinddir()
• 디렉토리 파일의 current file offset을 처음으로 옮긴다. (첫 번째 엔트리로 옮긴다.)
closedir()
• 디렉토리 파일을 닫는다.
• 리턴 값: 성공하면 0, 실패하면 -1
#include <sys/types.h>#include <dirent.h>
void rewinddir (DIR *dp);int closedir (DIR *dp);
23
Page 45UNIX System Programmingby Yang-Sae Moon
mkdirmkdir()()APUE (Files & Directories)
새로운 디렉토리를 만든다.
리턴 값: 성공하면 0, 실패하면 -1
성공하면, “.”와 “..” 파일은 자동적으로 만들어진다.
• “.”은 현재 디렉토리 파일의 i-node를,
• “..”은 부모 디렉토리 파일의 i-node를 각각 가리킨다.
#include <sys/types.h>#include <sys/stat.h>
int mkdir (const char *pathname, mode_t mode );
Page 46UNIX System Programmingby Yang-Sae Moon
rmdirrmdir()()APUE (Files & Directories)
비어있는 디렉토리를 삭제한다.
리턴 값: 성공하면 0, 실패하면 -1
#include <unistd.h>
int rmdir (const char *pathname );
24
Page 47UNIX System Programmingby Yang-Sae Moon
예제예제: : listfiles.clistfiles.c (1/5)(1/5)
#include <sys/types.h> // listfiles.c#include <sys/mkdev.h>#include <sys/stat.h>#include <dirent.h>#include <stdio.h>
/* typeOfFile - return the letter indicating the file type. */char typeOfFile(mode_t mode) {switch (mode & S_IFMT) {case S_IFREG: return('-');case S_IFDIR: return('d');case S_IFCHR: return('c');case S_IFBLK: return('b');case S_IFLNK: return('l');case S_IFIFO: return('p');case S_IFSOCK: return('s');
}return('?');
}
APUE (Files & Directories)
Page 48UNIX System Programmingby Yang-Sae Moon
예제예제: : listfiles.clistfiles.c (2/5)(2/5)
/* permOfFile - return the file permissions in an "ls"-like string. */char* permOfFile(mode_t mode) {int i;char *p;static char perms[10];
p = perms;strcpy(perms, "---------");for (i=0; i < 3; i++) {if (mode & (S_IREAD >> i*3)) *p = 'r';p++;if (mode & (S_IWRITE >> i*3)) *p = 'w';p++;if (mode & (S_IEXEC >> i*3)) *p = 'x';p++;
}if ((mode & S_ISUID) != 0) perms[2] = 's';if ((mode & S_ISGID) != 0) perms[5] = 's';
return(perms);}
APUE (Files & Directories)
25
Page 49UNIX System Programmingby Yang-Sae Moon
예제예제: : listfiles.clistfiles.c (3/5)(3/5)
/* outputStatInfo - print out the contents of the stat structure. */void outputStatInfo(char *pathname, char *filename, struct stat *st) {int n;char slink[BUFSIZ+1];
printf("%5d ", st->st_blocks);printf("%c%s ", typeOfFile(st->st_mode), permOfFile(st->st_mode));printf("%3d ", st->st_nlink);printf("%5d/%-5d ", st->st_uid, st->st_gid);
if (((st->st_mode & S_IFMT)!=S_IFCHR) && ((st->st_mode & S_IFMT)!=S_IFBLK))printf("%9d ", st->st_size);
else printf("%4d,%4d ", major(st->st_rdev), minor(st->st_rdev));
printf("%.12s ", ctime(&st->st_mtime) + 4);printf("%s", filename);if ((st->st_mode & S_IFMT) == S_IFLNK) {if ((n = readlink(pathname, slink, sizeof(slink))) < 0)printf(" -> ???");
else printf(" -> %.*s", n, slink);}
}
APUE (Files & Directories)
Page 50UNIX System Programmingby Yang-Sae Moon
예제예제: : listfiles.clistfiles.c (4/5)(4/5)
int main(int argc, char **argv) {DIR *dp;char *dirname;struct stat st;struct dirent *d;char filename[BUFSIZ+1];/* For each directory on the command line... */while (--argc) {dirname = *++argv;if ((dp = opendir(dirname)) == NULL) /* Open the directory */perror(dirname);
printf("%s:\n", dirname);while ((d = readdir(dp)) != NULL) { /* For each file in the directory... *//* Create the full file name. */sprintf(filename, "%s/%s", dirname, d->d_name);if (lstat(filename, &st) < 0) /* Find out about it. */perror(filename);
outputStatInfo(filename, d->d_name, &st); /* Print out the info. */putchar('\n');
}putchar('\n');closedir(dp);
}return 0;
}
APUE (Files & Directories)
26
Page 51UNIX System Programmingby Yang-Sae Moon
예제예제: : listfiles.clistfiles.c (5/5)(5/5)APUE (Files & Directories)
실행 결과
Page 52UNIX System Programmingby Yang-Sae Moon
chdirchdir(), (), fchdirfchdir()()APUE (Files & Directories)
현재 작업 디렉토리를 변경한다. ($ cd)
반환 값: 성공하면 0, 실패하면 -1
현재 작업 디렉토리는 프로세스의 속성
(프로세스의 working directory가 변하는 것임)
#include <unistd.h>int chdir (const char *pathname);int fchdir (int filedes);
27
Page 53UNIX System Programmingby Yang-Sae Moon
getcwdgetcwd()()APUE (Files & Directories)
현재 작업 디렉토리의 경로명을 얻는다. ($ pwd)
반환 값: 성공하면 buf의 주소, 실패하면 NULL
#include <unistd.h>
char *getcwd (char *buf, size_t size );
Page 54UNIX System Programmingby Yang-Sae Moon
예제예제: : chdirchdir(), (), getcwdgetcwd() (1/2)() (1/2)
#include <unistd.h> // ncd.c#include <stdio.h>#define PATH_MAX 1024
int main(int argc, char **argv){char path[PATH_MAX+1];
if (argc == 1) exit(-1);
if (argc == 2) {if(getcwd(path, PATH_MAX) == NULL) perror("error getcwd");else printf("Current working directory changed to %s \n", path);
if(chdir(argv[1]) < 0) perror("error chdir");else {
if(getcwd(path, PATH_MAX) == NULL) perror("error getcwd");else printf("Current working directory changed to %s \n", path);
}} elseperror("Too many arguments");
}
APUE (Files & Directories)
28
Page 55UNIX System Programmingby Yang-Sae Moon
예제예제: : chdirchdir(), (), getcwdgetcwd() (2/2)() (2/2)APUE (Files & Directories)
실행 결과
Page 56UNIX System Programmingby Yang-Sae Moon
sync(), sync(), fsyncfsync()()APUE (Files & Directories)
버퍼에 있는 내용을 디스크에 쓰도록 한다.
sync()는 시스템 데몬 프로세스에 의해서 30초마다 호출된다.
fsync()는 지정된 파일에 대해서만 I/O 작업을 수행하도록 한다.
참고) O_SYNC 플래그 (모든 write()를 sync mode로 처리함)
#include <unistd.h>
void sync();int fsync(int filedes);