System Calls - File and Directory
Definition
File
- A container to contain data of a file (provides a linear space so that stores the data linearly).
- Each file has a low-level name (inode number).
Directory
- An implement directory tree (directory hierarchy).
- It also has a low level name.
- It contains a list of file name and inode number pair.
File Operations
open System Call
- Syntax:
int open(const char *pathname, int oflags);O_RDONLY: Read onlyO_WRONLY: Write onlyO_RDWR: Read and write.O_CREAT: If the pathname does not exist, create it as a regular file.O_TRUNC: If the file already exists and is a regular file and the access mode allows writing, it will be truncated to length 0.
- Return:
- file descriptor which is an integer to access files.
open Process
After executing
opensystem call, it undergoes:- The file descriptor specifies the index into File Descriptor Table (FDT) of the process.
- The entries of FDT contain pointers to entries in the System File Table (SFT).
- When a file is opened, an entry is created in both FDT and SFT.
SFT entry contains information about whether a file is open for read, write, protection, or lock and the file offset.

The file descriptor for the created file is
3.- Because when a process is created, file descriptor
0,1,2are opened by the default for standard input, output and error.
read System Call
- Syntax:
ssize_t read(int fd, void *buf, size_t count);fd: file descriptorbuf: buffer pointercount: the number of bytes to write to
- Return:
- the number of bytes it read.
write System Call
- Syntax:
ssize_t write(int fd, const *buf, size_t count);fd: file descriptorbuf: buffer pointercount: the number of bytes to write to
- Return:
- the number of bytes it write.
lseek System Call
- Description:
- An open file has a current offset to determine where the next read or write will begin reading from or writing to within the file.
lseekis used to update the current offset explicitly.
- Syntax:
off_t lseek(int fd, off_t offset, int whence);fd: file descriptoroffset: position the file offset to particular location within the filewhence: determine how the seek is performedSEEK_SET: the offset is set to offset bytes (offset)SEEK_CUR: the offset is set to offset bytes + its current location (offset + current)SEEK_END: the offset is set to offset bytes + the size of the file (offset + the end)
Examples
- File Operations:
1
2
3
4
5
6
7
8
9
10
11
12
13
14char buf[20] = "Hello World!";
char rbuf1[20];
// open or create "myfile"
int fd = open("myfile", O_CREAT | O_TRUNC | O_RDWR, S_IRUSR | S_IWUSR );
write(fd, buf, 20); // write buf into fd
lseek(fd, 0, SEEK_SET); // update the offset to the start
read(fd, rbuf1, 20); // read the content in fd (buf) and store into rbuf1
printf("%s\n", rbuf1); // Hello World!
lseek(fd, 6, SEEK_SET); // update the offset to the start + 6
read(fd, rbuf2, 20); // read the content and store into rbuf2
printf("%s\n", rbuf2); // World!
I/O Redirection
Redirection
Redirection
- it means that the process modifies its File Descriptor Table (FDT) entry so that it points to a different entry in the System File Table (SFT).
Example
- The command
catreads from a file and echoes to standard output - Suppose the
myfilecontains “Hello World” content,ls -l > myfilecommand redirects standard output tomyfile:1
2
3cat myfile # output: Hello World
ls -l > myfile
cat myfile # execute ls -l - Coding
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19/* 6-2-redirection-exec */
main(){
char *cmd = "ls";
char *argv[5];
argv[0] = "ls";
argv[1] = "-l";
argv[2] = ">";
argv[3] = "myfile";
argv[4] = NULL;
execvp(cmd, argv);
return 0;
}
- The command
dup System Call
Description:
dupis a smart function that can duplicate (copy) the file descriptorfdto the lowest-numbered unused file descriptor in the File Descriptor Table (FDT).Syntax:
int dup(int fd)fd: file descriptor
Return:
- Success, return a new file descriptor
- Error, return
-1
Example:
- Redirects standard output
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27/* 6-redirection */
int main(){
char *cmd;
char *argv[3];
int fd = open("myfile", O_CREAT |O_TRUNC |O_RDWR, S_IRUSR| S_IWUSR );
close(1); // Close the stdout
dup(fd); // Duplicate fd
close(fd);
cmd = "ls";
argv[0] = "ls";
argv[1] = "-l";
argv[2] = NULL;
execvp(cmd, argv);
return 1;
}1
cat myfile # execute ls -l
- Redirects standard output
Processes Communication
pipe System Call
- Description:
- Pipes provide a unidirectional interprocess communication channel.
- A pipe has a read end and a write end.
- Data is written to the write end of a pipe can be read from the read end of the pipe.
- If a process attempts to read from an empty pipe, then
read()will block until the data is available.
Situations:
- If all file descriptors referring to the write end of a pipe have been closed, then an attempt to
read()from the pipe will see end-of-file. - If all file descriptors referring to the read end of a pipe have been closed, then a
write()will cause a SIGPIPE signal to be generated for all the calling process.- If the calling process is ignoring the signal, then
write()fails with the error EPIPE.
- If the calling process is ignoring the signal, then
- If all file descriptors referring to the write end of a pipe have been closed, then an attempt to
Syntax:
int pipe(int* fd);fd[0]: the read endfd[1]: the write end
Return:
- Success: return
0 - Error: return
-1
- Success: return
Example:
- counting the lines of output in executing
ls -l1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56/* 7-pipe */
main(){
int fd[2];
int ret;
char *cmd;
char *argv[3];
pipe(fd);
if ((ret=fork()) > 0){
/*
Parent Process
We want to use parent process executes "ls -l", so do redirection
We want to redirect the standard output to the write end of pipe
*/
close(1); // close standard output
dup(fd[1]); // fd[1] is duplicated to standard output
close(fd[0]);
close(fd[1]);
cmd = "ls";
argv[0] = "ls";
argv[1] = "-l";
argv[2] = NULL;
execvp(cmd, argv);
}else if(ret == 0){
/*
Child Process
We want to use child process executes "wc -l", so do redirection
We want to redirect the standard input to the read end of pipe
to get the input from the parent process
*/
close(0); // close standard input
dup(fd[0]); // fd[0] is duplicated to standard input
close(fd[0]);
close(fd[1]);
cmd = "wc";
argv[0] = "wc";
argv[1] = "-l";
argv[2] = NULL;
execvp(cmd, argv);
}
}
- counting the lines of output in executing
Other Operations
fsync Write Immdeiately
Description:
- The file system will buffer writes in memorys for some time, so the write(s) will actually be issued to the storage device, like data lost.
fsyncsystem call forces all dirty data written to disk immediately, and returns after all these writes were completed.
Syntax:
int fsync(int fd)Return:
- Success: return
0 - Error: return
-1
- Success: return
rename Rename File
Syntax:
rename(char* old, char* new)Example:
1
2
3
4
5
6int fd = open("foo.txt.tmp", O_WRONLY | O_CREAT | O_TRUNC, S_IRWXU);
char buffer[20] = "hello";
write(fd, buffer, sizeof(buffer));
fsync(fd);
close(fd);
rename("foo.txt.tmp", "foo.txt");
fstat Show Information
Show the file metadata (the information about the file).
Structure:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15struct stat {
dev_t st_dev; /* ID of device containing file */
ino_t st_ino; /* inode number */
mode_t st_mode; /* protection */
nlink_t st_nlink; /* number of hard links */
uid_t st_uid; /* user ID of owner */
gid_t st_gid; /* group ID of owner */
dev_t st_rdev; /* device ID (if special file) */
off_t st_size; /* total size, in bytes */
blksize_t st_blksize; /* blocksize for filesystem I/O */
blkcnt_t st_blocks; /* number of blocks allocated */
time_t st_atime; /* time of last access */
time_t st_mtime; /* time of last modification */
time_t st_ctime; /* time of last status change */
};
- Example:
1
2echo hello > file # create and write "hello" into file
stat file # show the information of file
Directories Operations
Create Directories
mkdirsystem call- Make an empty directory, which contains two entries:
.(itself) and..(parent).
Read Directories
opendirsystem call: open directoryreaddirsystem call: read directory entries (similar tols).
Remove Directories
rmdirsystem call- It requires the directory is empty.
- Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int main(int argc, char *argv[]){
DIR *dp = opendir("."); // open current directory
assert(dp != NULL);
struct dirent *d;
while ((d = readdir(dp)) != NULL) // read one directory entry
{
// print outthe name and inode number of each file
printf("%d %s\n", (int) d->d_ino, d->d_name);
}
closedir(dp); // close current directory
return 0;
}
Links
Hard Links
Description:
- Creare another name in the directory and refer it to the same inode number (same file) of the original file.
Noted: Hard link does not really create a file, it just creates a link which linking to the original file.
Editting the old file would change the content in new file.
1
2
3
4
5
6
7echo hello > file
ln file file2 # create a hard link, link file to file2
echo helloworld > file
cat file2 # helloworld
ls -i file file2
4633749 file 4633749 file2 # they have the same inode value
Syntax:
- system call:
link(char* "oldpath", char* "newpath"); - command:
ln oldpath newpath
- system call:
Remove File:
- That’s why we call
unlinkto remove file.1
2
3
4echo hello > file
ln file file2 # create a hard link, link file2 to file
rm file # remove file
cat file2 # file2 can still access the file
- That’s why we call
Symbolic Links
Description:
- It can create for a directory (hard link cannot).
1
2
3mkdir foo
ln foo foo1 # ln: foo: Is a directory
ln -s foo foo1
- It can create for a directory (hard link cannot).
Difference:
- File system knows that symbolic link is a third type (different type), so symbolic link does just create a new file.
- The size of symbolic link is 4 bytes
1
2
3ls -a
# -rw-r--r-- ... 6 file
# lrwxr-xr-x ... 4 file2 -> file
Remove File:
- When the original file was removed, symbolic link points nothing
1
2
3
4echo hello > file
ln -s file file2
rm file
cat file2 # cat: file2: No such file or directory
- When the original file was removed, symbolic link points nothing


