Chap.7 데이터의 저장 - 파일

Unix File System

• File I/O

- Algorithm: 연산들의 집합

- 특징: 이산성, 정확성, 효율성, 끝나야한다, 한계성

protocol의 특성?

▪ file name

- upto 255 chars.

- without / or '\0' (null char.).

▪ pathname

- relative pathname : the path begins at the current working dir.

ex) doc/book/chap1.txt

- absolute pathname : the path begins at the "root" dir.

ex) /user/prof/tykim/doc/book/chap1.txt

▪ File descriptor

- a process uses an integer to identify a file that has been opened for I/O.

ex) #include <fcntl.h>

int open(char *pathname, int oflg[, int mode]);

□ open()을 수행한 후 돌려 받는 int 값

c.f. fopen()  ; C-compiler function.

- special file descriptor :  파일이 open되면 기본적으로 open되는 descriptor.

0 : stdin .... standard input - keyboard         <: input redirection

1 : stdout .... standard output - monitor        >: output    〃

2 : stderr .... standard error 출력 - monitor     2>: error    〃

⇒ I/O device도 (special) file로 취급.

ex)

while (cc = getc(stdin) != EOF)	; NO fopen() or fclose()

putc(cc, stdout);

▪ Socket descriptor

- An integer used to identify a socket that has been opened for N/W comm.

ex)	#include <sys/types.h>

#include <sys/socket.h>

int socket(int family, int types, int protocol);  chap. 6 참고

▪ I/O function in Unix

Server

Client

comm. I/O

file I/O

system call

file I/O

C library routine

socket()

↓

connect()

socket()

↓

bind()

↓

listen()

↓

accept()

↓

open()

↓

read()

↓

write()

↓

close()

fopen()

↓

fscan(), fgetc(),

↓

fprintf(), fputc(),

↓

fclose()

read() ……  write()

write() ……  read()

close() …… close()

ex) p.261 figure 6.2 : connection-oriented protocol [TCP의 경우]

p.262 figure 6.3 : connectionless protocol [UDP의 경우]

▪ Structure of the Unix file system

① file descriptor table

․in user block.

․a file descriptor is just a index number.

․open()에 의해 process가 I/O로 사용할 file을 point함.

② file table

․file descriptor table과 inode table 사이에 위치.

․하나의 file을 여러 process가 공유할 수 있게 함.

ex) file sharing: p.71 fig.2-12

① dup()에 의한 공유.

② fork()에 의한 공유.

③ pipe()에 의한 공유.   ex) ls | more

③ inode table

․OS가 file을 운영하는데 필요한 자료 구조.

▪Process들이 하나의 File을 공유하는 경우

⇒ Mutual Exclusion 기능

한글 WP

한글 WP

논문.hwp

R/W

R only

c.f. Wordpad??

▪ File type

① regular file (ordinary file): contain zero or more data bytes.

② directory : contains the names and i_node no.'s of other files.

ex) directory D1의 자료구조.

/

f1

x

D4

D3

i_node table

D1

i_number	file name
144	․
1	‥
96	f1
326	D3
0	x
147	D4

i_number of root

directory = 1

만약 delete되면

i_node가 0로

되고, 다음 file

생성시에 재사용

#define MAXNAMELEN 255

struct direct {

u_long d_ino;    /* i_node no. */

u_short d_reclen;

u_short d_numlen;

char d_name[MAXNAMELEN+1];

}               /* file_name + '\0' */

ex)	디렉토리에 속한 파일명, 파일 갯수를 출력하는 프로그램

#include <sys/types.h>

#include <sys/dir.h>

#include <fcntl.h>

my_ls(name)

char	*name;	/* directory name */

{

struct direct d;	int cnt = 0;	int fd;

if ((fd = open(name, O_RDONLY)) < 0)	return(-1);

while((read(fd, (char *)&d, sizeof(d)) == sizeof(d))

{             /* 읽을 buffer, 읽을 byte 수, 읽어들인 byte 수 */

if (d.d_ino != 0){

printf("%14s\n", d.d_name);     /* 14 chars 출력 */

cnt++;

}                                       /* 출력결과     */

}                                             /* .             */

printf("Total of %d files \n", cnt);            /* ..            */

close(fd);	/* f1           */

return(0);	/* D3          */

}	/* D4          */

③ special file: I/O devices appear as regular files.

- character s. f. : CRT(/dev/tty), printer, modem 등.

- block s. f. : disk(/dev/ra0a), tape driver 등.

ex) > df   /* file system list.  ex) C: & D: in one disk */

ex) 100개의 문자 “x"를 단말기 "tty00"에 출력

#include <fcntl.h>

main()

{

int i, fd;

fd = open("/dev/pts/1", O_WRONLY);  /* virtual terminal, Solaris */

for (i = 0; i < 100; i++)

write(fd, "x", 1);

close(fd);       /* 출력할 byte 수 */

}

④ FIFO : a named pipe. (in system V)

ex) > ls | more	/* ls   : a producer process - write into a file.

more: a consumer process - read from a file.

|    : pipe - a temporary file.

⑤ symbolic link : a file that contains the pathname of another file. (in

4.3BSD)

ex)  >ls -al

/usr/include/sys/log.h -> /sys/termins.h

ex) link(), unlink() system call 사용. (혹은 link, unlink command)

link("abc", "xyz“);

> ls                   d_ino  d_name

xyz → abc	235   abc'\0'

235	xyz'\0'

⑥ socket : a special type of file for comm.

ex) p.29 program

ex) # ls -al

-rwxrwxrwx  1 smith  dev    10876  May 16 9:42 part2

Reading from right to left,

- the current  directory  holds one file, named part2.

- the last time that file's contents were modified was 9:42 A.M. on May 16.

- the file contains 10,876 characters, or bytes.

- the owner of the file, or the user, belongs to the group dev  (perhaps  indicating ``development''), and his or her login name is smith.

- the number, in this case 1, indicates the number of links to file part2.

(file의 경우, 1이고, directory의 경우, directory가 갖고 있는 file 수)

- the  dash  and letters  tell  you that user, group, and others have permissions to read, write, and execute part2.

- file type

-   the entry is an ordinary file;

d   the entry is a directory;

b   the entry is a block special file;

c   the entry is a character special file;

p   the entry is a fifo (or "named pipe") special file;

l   the entry is a symbolic link;

s   the entry is an AF_UNIX address family socket;

- file type에 관한 정보

p.29  stat 구조체 in <sys/stat.h>

ushort	st_mode

- st_mode의 각 비트들이 어떤 정보들을 각각 나타내는가?

1   1 1 1   0 0 0   0 0 0   0 0 0   0 0 0

file type           user    group   other

Save text image after execution("sticky bit")

Set group ID on execution

Set user ID on execution

-p.29 <sys/stat.h>의 file type 정의

#define	S_IFMT	0170000	/* type of file */

#define	S_IFREG	0100000	/* regular */

#define	S_IFDIR	0040000	/* directory */

#define	S_IFCHR	0020000	/* character special */

#define	S_IFBLK	0060000	/* block special */

#define	S_IFLNK	0120000	/* symbolic link - BSD only */

#define	S_IFSOCK	0140000	/* socket - BSD only */

#define	S_IFIFO	0010000	/* fifo - System V only */

ex) p.30 program

ex) > my_ls test.txt

/* my_ls.c - display info. about a file */

#include <stdio.h>

#include <sys/types.h>

#include <sys/stat.h>

/* use octal array for determining if perm. bits set */

static short octarray[9]={ 0400,0200,0100,

0040,0020,0010,

0004,0002,0001};

/* mnemonic codes for file perm. - 10 chars because of ending null */

static char perms[]="rwxrwxrwx";

/* main function */

main(argc,argv)

int argc;

char *argv[];

{

if (argc<2)	fprintf(stderr,"Usage: myls [filename]\n");

filedata(argv[1]);

}

filedata(pathname)

char *pathname;

{

struct stat statbuf;

char descrip[9];

int i;

if (stat(pathname,&statbuf)<0){

fprintf(stderr,"Couldn't stat %s\n",pathname);

return(-1);

}

/* put perm. into readable form */

for(i=0;i<9;i++){

if (statbuf.st_mode & octarray[i])

descrip[i]=perms[i];

else

descrip[i]='-';

}

descrip[9]='\0';

printf("\nFile: %s\n",pathname);

printf("Size: %ld bytes\n",statbuf.st_size);

printf("User-id: %d,  Group-id: %d\n",statbuf.st_uid,statbuf.st_gid);

printf("Permissions: %s\n\n",descrip);

return(0);

}

ex) > lookout test1.txt test2.txt text3.txt &

/* lookout.c - monitoring files and print a message when file changes */

#include <stdio.h>

#include <sys/types.h>

#include <sys/stat.h>

#define MFILE 10            /* monitoring할 file의 max. 개수 */

struct stat sb;

main(argc,argv)

int argc;

char *argv[];

{

int i;

time_t last_time[MFILE+1];

if (argc<2){

fprintf(stderr,"Usage: lookout [filename]...\n");

exit(1);

}

if (--argc>MFILE){

fprintf(stderr,"lookout too many file names...\n");

exit(1);

}

for(i=1;i<argc;i++){

if (stat(argv[i],&sb)<0){

fprintf(stderr,"lookout: couldn't stat %s\n",argv[i]);

exit(1);

}

last_time[i]=sb.st_mtime;    /* file이 변경된 시간을 저장 */

}

/* loop until file changes */

for(;;){

for(i=1;i<=argc;i++){

cmp(argv[i],last_time[i]);   /* 10초마다 st_mtime을 비교 */

/* rest for 10 secs */

sleep(10);

}

}

}

cmp(name,last)

char *name;

time_t last;

{       /* file이 없어지거나 변경되었을 때 */

if (stat(name,&sb)<0 || sb.st_mtime !=last){	/* OR,  c.f. &&: AND */

fprintf(stderr,"lookout: %s changed\n",name);

exit(0);

}

}