Presentation is loading. Please wait.

Presentation is loading. Please wait.

제2부 시스템 프로그래밍 파일 및 입출력 2011 가을 숙명여대 창병모 © 숙대 창병모.

Similar presentations


Presentation on theme: "제2부 시스템 프로그래밍 파일 및 입출력 2011 가을 숙명여대 창병모 © 숙대 창병모."— Presentation transcript:

1 제2부 시스템 프로그래밍 파일 및 입출력 2011 가을 숙명여대 창병모 © 숙대 창병모

2 목표 파일의 구조 및 특성을 이해한다. 파일을 열고 닫는다. 파일로부터 데이터를 읽고 쓴다. 현재 파일 위치 변경
기타 파일 제어 © 숙대 창병모

3 System Call (시스템 호출) © 숙대 창병모

4 System architecture of UNIX
Hardware CPU, Memory, Disk, Peripherals Kernel Process management File management Memory management Device management System call the programmer's functional interface to the UNIX kernel Commands, Utilities, Application programs kernel services using library routines or system calls © 숙대 창병모

5 System architecture of UNIX
© 숙대 창병모

6 System Call Process Process Process System call interface
File Management IPC Process Management © 숙대 창병모

7 System Call UNIX 커널에 서비스를 요청하기 위한 프로그래머 인터페이스
© 숙대 창병모

8 File I/O © 숙대 창병모

9 What is a file ? a file is a contiguous sequence of bytes
no format imposed by the operating system each byte is individually addressable in a disk file a file is also a uniform interface to external devices © 숙대 창병모

10 File Descriptor File descriptor open() returns a fd, an integer value
열린 파일을 나타내는 번호(파일 식별자) used in subsequent I/O operations on that file close(fd) closes that file described by fd © 숙대 창병모

11 File Descriptor file descriptor : 0 ~ 19 © 숙대 창병모

12 User and Kernel Mode Kernel User process open(char *name, int mode) {
Address of kernel close() result=open(“/usr/glass/file.txt” , O_RDONLY); Address of kernel open() User code Address of kernel write() open(char *name, int mode) { <Place parameters in registers> <Execute trap instruction, switching to kernel code > <Return result of system call> } kernel code for open() { <Manipulate kernel data> . . . <Return to user code> } Kernel system call code C runtime library © 숙대 창병모

13 open() - 열기 #include <sys/types.h> #include <sys/stat.h>
#include <fcntl.h> int open (const char *pathname, int oflag, [ mode_t mode ]); 파일을 연다 파일이 없으면 경우에 따라 새로 만들어 질 수도 있다 리턴 값 : 파일 디스크립터(file descriptor), 실패하면 -1 pathname : 파일의 이름 mode : 파일의 access permission 값. 생략가능. 새로운 파일을 만드는 경우에만 사용됨 © 숙대 창병모

14 open() 의 파라미터 두 번째 파라미터 oflag는 다음 상수들의 OR 이다 반드시 하나 지정해주어야 할 값
int fd; fd = open("afile", O_RDWR | O_CREAT, 0600 ); 반드시 하나 지정해주어야 할 값 O_RDONLY : 읽기 모드, write 함수를 사용 할 수 없음 O_WRONLY : 쓰기 모드, read 함수를 사용 할 수 없음 O_RDWR : 읽고 쓰기 모드, read write 사용 가능 © 숙대 창병모

15 open() 의 파라미터 선택적 지정 가능 O_APPEND: 모든 write 된 데이터는 파일의 끝에 추가
O_CREAT : 파일이 없는 경우 파일 생성 세 번째 인자 mode O_EXCL : O_CREAT이고 그 파일이 이미 있으면 에러 O_TRUNC : 파일이 있는 경우 파일 크기를 0으로 만든다 O_NONBLOCK : nonblocking 모드로 입출력을 함 O_SYNC : 각 write 함수 호출은 디스크에 물리적으로 쓴 후 리턴한다 © 숙대 창병모

16 open() - 예 fd = open("account",O_RDONLY);
open a file for reading fd = open("account",O_RDONLY); open a file for writing fd = open("tmpfile", O_WRONLY|O_CREAT|O_TRUNC,0600); open a file for appending fd = open("/sys/log”,O_WRONLY|O_APPEND|O_CREAT,0600); open a file for reading and writing fd = open(argv[1], O_RDWR); create a new file for writing if ((fd = open("tmpfile", O_WRONLY|O_CREAT|O_EXCL, 0666))==-1) © 숙대 창병모

17 예제: open.c #include <stdlib.h> #include <fcntl.h> #include <unistd.h> int main(int argc, char *argv[]) { int fd; if ((fd = open (argv[1], O_RDWR)) == -1) perror(argv[1]); printf("%s is opened.\n", argv[1]); close(fd); return 0; } © 숙대 창병모

18 creat () - 파일 생성 #include <sys/types.h>
#include <sys/stat.h> #include <fcntl.h> int creat ( const char *pathname, mode_t mode ); 새로운 파일을 생성한다 리턴 값 : 파일 디스크립터, 실패하면 -1 pathname : 생성하고자 하는 파일의 이름 mode : 파일의 access permission 값 © 숙대 창병모

19 close () - 닫기 #include <unistd.h> int close ( int fd );
작업이 끝난 후 파일을 닫는다. fd : 닫고자 하는 파일의 파일 식별자 리턴 값 : 성공하면 0, 실패하면 -1 프로세스가 종료되면 모든 열려진 화일들은 자동적으로 닫힌다 © 숙대 창병모

20 read () - 읽기 #include <unistd.h>
ssize_t read ( int fd, void *buf, size_t nbytes ); fd가 나타내는 파일에서 데이터를 읽는다 nbytes 읽을 데이터의 바이트 수 buf 읽은 데이터를 저장할 메모리의 시작 주소 리턴 값: 성공하면 읽은 바이트 수 파일의 끝을 만나면 0 실패하면 -1 © 숙대 창병모

21 read () - 읽기 읽을 데이터가 충분하면 한 번에 nbytes 만큼 읽는다.
파일의 끝에서 네트웍 입출력에서 size_t : unsigned integer ssize_t : signed integer © 숙대 창병모

22 Read/Write - 예 Read Write charsRead = read(fd,buffer,BUFFER_SIZE);
if (charsRead == 0) break; /* EOF */ if (charsRead == -1) fatalError(); /*error */ Write charsWritten = write(tmpfd,buffer,charsRead); if (charsWritten != charsRead) fatalError(); © 숙대 창병모

23 예제 /* count.c: 파일의 문자 수를 센다*/
#include <stdlib.h> #include <fcntl.h> #include <unistd.h> #define BUFSIZE 512 int main() { char buffer[BUFSIZE]; int fd; ssize_t nread; long total = 0; if ((fd = open("afile", O_RDONLY)) == -1) perror("afile"); /* 파일의 끝에 도달할 때까지 반복 */ while( (nread = read(fd, buffer, BUFSIZE)) > 0) total += nread; close(fd); printf ("total chars in afile: %ld \n", total); return 0; } © 숙대 창병모

24 write() - 쓰기 #include <unistd.h>
ssize_t write (int fd, void *buf, size_t nbytes); fd가 나타내는 파일에 데이터를 쓴다 buf 쓸 데이터를 저장하고 있는 메모리의 시작주소 nbytes 쓸 데이터의 바이트의 수 리턴 값 성공하면, 파일에 쓰여진 데이터의 바이트 수 실패하면, -1 © 숙대 창병모

25 예: Copy Files #include <stdio.h> #include <fcntl.h> main(argc, argv) int argc; char *argv[ ]; { int fdin, fdout, n; char buf[BUFSIZE]; if (argc != 3) { fprintf(stderr,"Usage: %s filein fileout\n",argv[0]); exit(1); } if ((fdin = open(argv[1], O_RDONLY)) == -1) { perror(argv[1]); exit(2); } if ((fdout=open(argv[2],O_WRONLY|O_CREAT|O_TRUNC, 0644))==-1){ perror(argv[2]); exit(3);} while ((n = read(fdin, buf, BUFSIZE)) > 0) write(fdout, buf, n); exit(0); } © 숙대 창병모

26 현재 파일 위치 현재 파일 위치(current file offset) lseek()
파일을 처음 열면 현재 위치는 0 즉 파일의 시작 파일에 대한 읽기/쓰기는 현재 파일 위치에서 실행되어 읽기/쓰기 한 byte 수만큼 자동적으로 뒤로 이동 lseek() 임의의 위치로 파일의 현재 위치를 이동할 수 있다 current file offset © 숙대 창병모

27 File seek © 숙대 창병모

28 lseek() - 이동 #include <unistd.h>
off_t lseek (int fd, off_t offset, int whence ); 현재 파일 위치(current file offset)를 이동 성공하면 현재 위치를 리턴, 실패하면 -1 whence : 위치 기준점 SEEK_SET : 파일의 시작점 SEEK_CUR : 현재 위치 SEEK_END : 파일의 끝 offset : 기준점에서의 상대적인 거리 (byte 단위) SEEK_CUR, SEEK_END 와 같이 쓰일 때는 음수도 가능 © 숙대 창병모

29 예 :lseek rewind append record position increase file lseek(fd, 0L, 0);
loc = lseek(fd, 0L, 1); increase file lseek(fd, (long) MAX*sizeof(record), 2); write(fd, (char *) &reocrd, sizeof(record)); © 숙대 창병모

30 예제: /* lseek1.c */ #include <unistd.h> /* lseek1.c */ #include <fcntl.h> char buf1[] = "abcdefghij"; char buf2[] = "ABCDEFGHIJ"; int main() { int fd; if ( (fd = creat("file.hole", 0644)) < 0) perror("file.hole"); if (write(fd, buf1, 10) != 10) /* offset now = 10 */ perror("buf1"); if (lseek(fd, 40, SEEK_SET) == -1) /* offset now = 40 */ perror("lseek"); if (write(fd, buf2, 10) != 10) /* offset now = 50 */ perror("buf2"); return 0; } © 숙대 창병모

31 예제: /* lseek1.c */ lseek1.c 의 출력 파일 file.hole의 내용 1 2 3 4 5 6 7 8 9 a
1 2 3 4 5 6 7 8 9 a b c d e f g h i j 10 \0 20 30 40 A B C D E F G H I J © 숙대 창병모

32 예제: /* lseek2.c */ #include <sys/types.h> /* lseek2.c */ #include <unistd.h> #include <fcntl.h> int main() { int fd; off_t fsize; char buf[11]; if((fd=open("file.hole", O_RDONLY)) < 0) perror("file.hole"); fsize = lseek(fd, 0, SEEK_END); printf("size: %lu\n", fsize); lseek(fd, 40, SEEK_SET); read(fd, buf, 10); buf[10] = ‘\0’; puts(buf); return 0; } © 숙대 창병모

33 예: employee database Create employee file Query employee file
직원 정보를 읽어서 파일에 저장한다. 직웝 번호, 급여, 등 Query employee file 직원 번호를 이용하여 직원 정보를 질의한다. © 숙대 창병모

34 예: Creating an employee file
#include <fcntl.h> #include <stdio.h> #include "employee.h” main(argc, argv) int argc; char *argv[ ]; { int fd, open(), getpid(); struct employee record; if (argc < 2) { fprintf(stderr, "Usage: %s file\n", argv[0]); exit(1); } if ((fd = open(argv[1],O_WRONLY |O_CREAT|O_EXCL, 0640))==-1) { perror(argv[1]); exit(2); © 숙대 창병모

35 예: Creating an employee file
for (;;) { printf("Enter employee name <SPACE> salary:"); scanf("%s", record.name); if (record.name[0] == '.') break; scanf("%d", &record.salary); record.pid = getpid(); write(fd, (char *) &record, sizeof(record) ); } close(fd); exit(0); © 숙대 창병모

36 예: Creating an employee file
employee.h #define NAMESIZE 24 struct employee { char name[NAMESIZE] int salary; int pid; } © 숙대 창병모

37 예: Querying the employee file
#include <fcntl.h> #include "employee.h” main(argc, argv) int argc; char *argv[ ]; { int fd, recnum; struct employee record; if ((fd = open(argv[1], O_RDONLY)) == -1) { perror(argv[1]); exit(2); } © 숙대 창병모

38 예: Querying the employee file
for (; ; ) { printf(“\n Enter record number :”); scanf(“%d”, &recnum); if (recnum < 0) break; lseek(fd, (long)recnum*sizeof(record), 0); if (read(fd, (char *) &record, sizeof(record)) > 0) printf(“Employee:%s\tSalary:%d\n”, record.name, record.salary); else printf(“Record %d not found\n”, recnum); } close(fd); exit(0); © 숙대 창병모

39 레코드 수정 struct employee record; …
read(fd, (char *) &record, sizeof(record)); // … update record … // lseek(fd, (long) -sizeof(record), 1); write(fd, (char *) &record, sizeof(record)); © 숙대 창병모

40 레코드 수정 record READ current file offset © 숙대 창병모

41 레코드 수정 record LSEEK current file offset © 숙대 창병모

42 레코드 수정 record WRITE current file offset © 숙대 창병모

43 File status (파일 상태 정보) © 숙대 창병모

44 파일 상태(file status) 파일 상태 어떤 것들이 있을까요? 어디에 있나요? 파일 자체에 대한 데이터 파일 타입
파일 크기 소유자 허가권 어디에 있나요? i-node ©숙대 창병모

45 stat() 역할 리턴 값 #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 (int filedes, struct stat *buf ); 역할 파일에 대한 상태 정보를 가져와서 stat 구조체 buf에 저장한다. 리턴 값 성공하면 0, 실패하면 -1 ©숙대 창병모

46 stat 구조체 <sys/stat.h> 에 정의 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 */ }; ©숙대 창병모

47 stat 구조체 st_atime st_mtime st_ctime st_blksize st_blocks
마지막으로 파일의 데이터를 읽은 시각 st_mtime 마지막으로 파일의 데이터를 수정한 시각 st_ctime 파일의 내용이 아니고 이름/권한 같은 상태를 변경한 시각 st_blksize 가장 효율적인 I/O 블럭 크 (2장 8절 I/O 성능 참고, 8192 bytes) st_blocks 파일이 차지하고 있는 공간의 크기를 512 byte 블럭의 수로 ©숙대 창병모

48 파일 타입 보통 파일 (Regular file) 디렉토리 파일 (Directory file)
데이터를 포함하고 있는 텍스트 또는 이진 화일 디렉토리 파일 (Directory file) 파일의 이름들과 파일 정보에 대한 포인터들을 포함 문자 특수 파일 (Character special file) 시스템에 장착된 어떤 장치를 가리키는 파일 문자 단위로 데이터를 전송하는 장치 블록 특수 파일 (Block special file) 블럭 단위로 데이터를 전송하는 장치 ©숙대 창병모

49 파일 타입 FIFO 소켓 (socket) 심볼릭 링크 (Symbolic link) 프로세스 간 통신에 사용되는 파일
named pipe 라고도 불림 소켓 (socket) 네트웍을 통한 프로세스 간 통신에 사용되는 파일 심볼릭 링크 (Symbolic link) 다른 파일을 가리키는 포인터 역할을 하는 파일 ©숙대 창병모

50 파일 타입 검사 파일 타입을 검사하는 매크로 함수 해당 종류의 파일이면 1, 아니면 0 을 리턴
#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 값을 검사함 type special permission 4 3 9 st_mode ©숙대 창병모

51 예제: /* stat.c */ #include <sys/types.h>
#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); ©숙대 창병모

52 Change mode of file int chmod(char *path; int mode)
#include <stdio.h> main(argc, argv) int argc; char *argv[]; { long strtol( ); int newmode; newmode = (int) strtol(argv[1],(char **) NULL, 8); if (chmod(argv[2], newmode) == -1) { perror(argv[2]); exit(1); } exit(0); %setmode 755 file © 숙대 창병모

53 Change owner/group of a file
int chown(char *path, int owner, int group) Example % setown file1 file2 © 숙대 창병모

54 Change owner/group of a file
#include <sys/types.h> #include <sys/stat.h> main(argc, argv) int argc; char *argv[]; { struct stat stbuf; int stat( ), chown( ); if (argc < 3) { printf(“Usage: %s other-file your-file\n”,argv[0]); exit(1); } if (stat(argv[1], &stbuf) == -1) { perror(argv[2]); exit(2); if (chown(argv[2], stbuf.st_uid, stbuf.st_gid) == -1) { exit(3); exit(0); © 숙대 창병모

55 Set File Access/Modification Time
newtime #include <sys/types.h> int utime(char *path, struct utimebuf *times) %settime - file %settime file1 file2 © 숙대 창병모

56 예 : Changing File Times #include <stdio.h> #include <sys/types.h> #include <sys/stat.h> struct utimbuf { time_t actime; time_t modtime; } main(argc, argv) int argc; char *argv[ ]; { int stat(), utime(); struct stat stbuf; struct utimbuf timestamp, *times=&timestamp; © 숙대 창병모

57 예 : Changing File Times if (argv[1][0] != ‘-’) { if (stat(argv[1], &stbuf) == -1) { perror(argv[1]); exit(2); } times->actime = stbuf.st_atime; times->modtime = stbuf.st_mtime; else times = (struct utimbuf *) NULL; if (utime(argv[2], times) == -1) { perror(argv[2]); exit(3); exit(0); © 숙대 창병모

58 Directory © 숙대 창병모

59 What is a Directory A kind of file used to organize
regular, pipe, special files and other directory format imposed by Unix file names are contained only in directory entries permissions r: readable w: writable x: searchable ©숙대 창병모

60 Directory and File A Directory i-list name 36 inode data blocks
©숙대 창병모

61 Directory 디렉토리 파일 디렉토리 파일의 내용은 구조체 dirent의 배열
일종의 파일이므로 open, read, close 함수 등을 사용할 수 있다 디렉토리 파일 사용에 편리한 새로운 함수들도 제공된다. 디렉토리 파일의 내용은 구조체 dirent의 배열 d_name : 파일 이름, 하위 디렉토리 이름, ".", ".." d_ino: i-node number #include <dirent.h> struct dirent { ino_t d_ino; /* i-node number */ char d_name[NAME_MAX + 1]; /* filename */ } ©숙대 창병모

62 디렉토리 접근 opendir()로 디렉토리 파일을 열고 리턴 값 DIR 구조체
#include <sys/types.h> #include <dirent.h> DIR *opendir (const char *pathname); struct dirent *readdir(DIR *dp); opendir()로 디렉토리 파일을 열고 리턴 값 성공하면 DIR 구조체 주소, 실패하면 NULL DIR 구조체 열린 디렉토리를 나타내는 구조체 like FILE struct ©숙대 창병모

63 readdir() readdir() 디렉토리의 현재 파일 위치 직접 쓸 수 없다 디렉토리 내용을 읽는다
해당 디렉토리에 대한 읽기 권한이 있어야 한다 한번에 dirent 하나씩 읽는다. 디렉토리의 현재 파일 위치 읽을 때마다 읽은 구조체 dirent 크기 만큼 증가한다. 직접 쓸 수 없다 그러나 쓰기권한이 있어도 write 함수로 직접 쓸 수는 없다. mkdir rmdir 를 사용해야 함 ©숙대 창병모

64 예: List directory int main(int argc, char **argv) { DIR *dp;
char *dirname; struct stat st; struct dirent *d; char filename[BUFSIZ+1]; while (--argc) { // For each directory on the command line 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 sprintf(filename, "%s/%s", dirname, d->d_name); //full filename if (lstat(filename, &st) < 0) // Find out about it. perror(filename); outputStatInfo(filename, d->d_name, &st); // Print out the information putchar('\n'); } putchar('\n'); closedir(dp); return 0; © 숙대 창병모

65 예: List directory #include <sys/types.h> /* listfiles.c */ #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('?'); © 숙대 창병모

66 예: List directory /* 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'; if (mode & (S_IEXEC >> i*3)) *p = 'x'; } if ((mode & S_ISUID) != 0) perms[2] = 's'; if ((mode & S_ISGID) != 0) perms[5] = 's'; if ((mode & S_ISVTX) != 0) perms[8] = 't'; return(perms); © 숙대 창병모

67 예: List directory /* 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); } © 숙대 창병모

68 FILE STATUS: st_mode #define S_IFMT 0170000 /* type of file */
#define S_IFDIR /* directory */ #define S_IFREG /* regular file */ #define S_IFBLK /* block special */ © 숙대 창병모

69 디렉토리 생성: mkdir() 새로운 디렉토리를 만든다. 리턴 값 성공하면 "." 와 ".." 파일은 자동적으로 만들어진다.
#include <sys/types.h> #include <sys/stat.h> int mkdir (const char *pathname, mode_t mode ); 새로운 디렉토리를 만든다. 리턴 값 성공하면 0, 실패하면 -1 성공하면 "." 와 ".." 파일은 자동적으로 만들어진다. "."은 이 디렉토리 파일의 i-node를, ".."은 부모 디렉토리 파일의 i-node를 가르킨다 ©숙대 창병모

70 디렉토리 삭제: rmdir() 비어 있는 디렉토리를 삭제한다. 리턴 값 #include <unistd.h>
int rmdir (const char *pathname ); 비어 있는 디렉토리를 삭제한다. 디렉토리 파일의 link count를 감소 시킴 link count가 0이 되면 삭제됨 리턴 값 성공하면 0, 실패하면 -1 ©숙대 창병모

71 디렉토리 생성/삭제 예 main() { mkdir(“/tmp/D”, 0750); system(“ls -ld /tmp/D”); rmdir(“/tmp/D”); } © 숙대 창병모

72 Link to a File Directory1 i-list
int link(char *path1, char *path2) main(argc, argv) int argc; char *argv[ ]; { if (link(argv[1], argv[2]) == -1) exit(1); } exit(0) i-list path1 36 inode Directory2 data blocks path2 36 © 숙대 창병모

73 Unlink remove directory entry int unlink(char *path)
main(argc, argv) int argc; char *argv[ ]; { int unlink( ); if (unlink(argv[1]) == -1{ perror(argv[1]); exit(1); } exit(0); © 숙대 창병모


Download ppt "제2부 시스템 프로그래밍 파일 및 입출력 2011 가을 숙명여대 창병모 © 숙대 창병모."

Similar presentations


Ads by Google