Tuesday, November 11, 2014

Unix Prog: popen, pclose(2)

1. popen, pclose implementation
pipe.c:
 #include<stdio.h>  
 #include<stdlib.h>  
 #include<unistd.h>  
 #include<errno.h>  
 #include<fcntl.h>  
 #include<sys/wait.h>  
   
 // pointer to array allocated at run-time  
 static pid_t *childpid = NULL;  
   
 // From our open_max()  
 static int maxfd;  
   
 FILE *popen(const char *cmdstring, const char *type)  
 {  
  int i;  
  int pfd[2];  
  pid_t pid;  
  FILE *fp;  
   
  // only allow "r" or "w"  
  if((type[0] != 'r' && type[0] != 'w') || type[1] != 0) {  
   errno = EINVAL;  
   return NULL;  
  }  
   
  // first time to allocate childpid  
  if(childpid == NULL) {  
   maxfd = 4096;  
   if((childpid = calloc(maxfd, sizeof(pid_t))) == NULL) {  
    return NULL;  
   }  
  }  
   
  // Setup the pipe  
  if(pipe(pfd) < 0) return NULL;  
   
  // Create the child process  
  if((pid = fork()) < 0) {  
   return NULL;  
  } else if(pid == 0) { // child process  
   // Handle the pipe file descriptor  
   if(*type == 'r') {  
    close(pfd[0]);  
    if(pfd[1] != STDOUT_FILENO) {  
     dup2(pfd[1], STDOUT_FILENO);  
     close(pfd[1]);  
    }  
   } else {  
    close(pfd[1]);  
    if(pfd[0] != STDIN_FILENO) {  
     dup2(pfd[0], STDIN_FILENO);  
     close(pfd[0]);  
    }  
   }  
   
   // close all existing descriptors which is opened before  
   // this is required by POSIX.1 standard  
   for(i = 0; i < maxfd; i++)  
    if(childpid[i] > 0)  
     close(i);  
   
   // Execute the descriptors  
   execl("/bin/sh", "sh", "-c", cmdstring, (char*)0);  
   _exit(127);  
  }  
   
  // parent process open the file stream from pipe descriptor  
  if(*type == 'r') {  
   close(pfd[1]);  
   if((fp = fdopen(pfd[0], type)) == NULL) return NULL;  
  } else {  
   close(pfd[0]);  
   if((fp = fdopen(pfd[1], type)) == NULL) return NULL;  
  }  
   
  childpid[fileno(fp)] = pid;  
  return fp;  
 }  
   
 int pclose(FILE* fp)  
 {  
  int fd, stat;  
  pid_t pid;  
   
  // popen has never been called.  
  if(childpid == NULL) {  
   errno = EINVAL;  
   return -1;  
  }  
   
  fd = fileno(fp);  
   
  // fp wasn't opened by popen()  
  if((pid = childpid[fd]) == 0) {  
   errno = EINVAL;  
   return -1;  
  }  
   
  childpid[fd] = 0;  
  if(fclose(fp) == EOF)  
   return -1;  
   
  while(waitpid(pid, &stat, 0) < 0) {  
   if(errno != EINTR)  
    return -1;  
  }  
   
  return stat;  
 }  
   
 int main(int argc, char* argv[])  
 {  
  exit(0);  
 }  

Note: popen should never be called by a set-user-id or set-group-id program. when it executes the command with the environment inherited by the caller.
A malicious user can manipulate the environment so that the shell executes commands other than those intended, with the elevated permissions granted by the set-ID file mode.

If the parent process setup the signal handler for SIGCHLD, waitpid is interrupted when child process exits, at this time, errno == EINTR, then we simply retry waitpid again (while waitpid loop).

Unix Prog: popen, pclose(1)

1. popen pclose
System Definition
 ubuntu@ip-172-31-23-227:~$ less /usr/include/stdio.h  
 ......  
 /* Create a new stream connected to a pipe running the given command.  
   
   This function is a possible cancellation point and therefore not  
   marked with __THROW. */  
 extern FILE *popen (const char *__command, const char *__modes) __wur;  
   
 /* Close a stream opened by popen and return the status of its child.  
   
   This function is a possible cancellation point and therefore not  
   marked with __THROW. */  
 extern int pclose (FILE *__stream);  
 ......  

The function popen does a fork and exec to execute the cmdstring, and returns a standard I/O file pointer. If type is "r", the file pointer is connected to the standard output of cmdstring.


If the type is "w", the file pointer is connected to the standard input of cmd string.


The cmd string will be executed by bourne shell which is:
sh -c cmdstring

2. Example:
pipe.c:
 #include<stdio.h>  
 #include<stdlib.h>  
 #include<unistd.h>  
 #include<sys/wait.h>  
   
 #define PAGER "/bin/more" // environment variable or default  
   
 int main(int argc, char* argv[])  
 {  
  char line[20];  
  FILE *fpin, *fpout;  
   
  // Open the existing file for input  
  if((fpin = fopen(argv[1], "r")) == NULL) {  
   printf("can't open %s", argv[1]);  
   exit(1);  
  }  
   
  // Fork a new process, execute the pager, leave standard input on  
  // So parent process can write to fpout that could pipe to pager input  
  if((fpout = popen(PAGER, "w")) == NULL) {  
   printf("popen error!\n");  
   exit(2);  
  }  
   
  // Write the content to the fpout which is piped to standard input  
  while(fgets(line, 20, fpin) != NULL) {  
   if(fputs(line, fpout) == EOF) {  
    printf("fputs error to pipe");  
    exit(3);  
   }  
  }  
   
  if(ferror(fpin)) {  
   printf("fgets error!\n");  
   exit(4);  
  }  
   
  // Close the file stream  
  if(pclose(fpout) == -1) {  
   printf("pclose error!\n");  
   exit(5);  
  }  
   
  exit(0);  
 }  

shell:
popen will make the pipe much easier.
 ubuntu@ip-172-31-23-227:~$ ./pipe.out test  
 hello world!  

Unix Prog: IPC Pipe(3)

1. Example:
pipe.c:
 #include<stdio.h>  
 #include<stdlib.h>  
 #include<unistd.h>  
   
 int pfd1[2], pfd2[2];  
   
 void TELL_WAIT(void)  
 {  
  // Create two pipes here, one for parent -> child  
  // another one for child -> parent  
  if(pipe(pfd1) < 0 || pipe(pfd2) < 0) {  
   printf("pipe error!\n");  
   exit(1);  
  }  
 }  
   
 void TELL_PARENT(pid_t pid)  
 {  
  if(write(pfd2[1], "c", 1) != 1) {  
   printf("write error!\n");  
   exit(2);  
  }  
 }  
   
 void WAIT_PARENT(void)  
 {  
  char c;  
   
  if(read(pfd1[0], &c, 1) != 1) {  
   printf("read error!\n");  
   exit(3);  
  }  
   
  if(c != 'p') {  
   printf("WAIT_PARENT: incorrect data");  
   exit(4);  
  }  
 }  
   
 void TELL_CHILD(pid_t pid)  
 {  
  if(write(pfd1[1], "p", 1) != 1) {  
   printf("write error!\n");  
   exit(2);  
  }  
 }  
   
 void WAIT_CHILD(void)  
 {  
  char c;  
   
  if(read(pfd2[0], &c, 1) != 1) {  
   printf("read error!\n");  
   exit(3);  
  }  
   
  if(c != 'c') {  
   printf("WAIT_CHILD: incorrect data");  
   exit(4);  
  }  
 }  
   
 int main(int argc, char* argv[])  
 {  
  exit(0);  
 }  

Description:
Besides using signal mechanism, we can also use pipes to implement the parent/child process synchronization facility. It creates 2 pipes, one for parent sending data to child, one for child sending data to parent. Following diagram can illustrate this.

Monday, November 10, 2014

Unix Prog: IPC Pipe(2)

1. Pipe Example:
pipe.c:
 #include<stdio.h>  
 #include<stdlib.h>  
 #include<unistd.h>  
 #include<string.h>  
   
 #define DEF_PAGER "/bin/more" // Default Pager program  
 #define MAXLINE 20  
   
 int main(int argc, char* argv[])  
 {  
  int n;  
  int fd[2];  
  pid_t pid;  
  char *pager, *argv0;  
  char line[MAXLINE];  
  FILE *fp;  
   
  // Open the file  
  if((fp = fopen(argv[1], "r")) == NULL) {  
   printf("can't open %s", argv[1]);  
   exit(1);  
  }  
   
  // Build the pipe  
  if(pipe(fd) < 0) {  
   printf("pipe error!\n");  
   exit(2);  
  }  
   
  if((pid = fork()) < 0) {  
   printf("fork error!\n");  
   exit(3);  
  } else if(pid > 0) {  
   close(fd[0]); // close read end  
   
   // Copy the content to pipe  
   while(fgets(line, MAXLINE, fp) != NULL) {  
    n = strlen(line);  
    if(write(fd[1], line, n) != n) {  
     printf("write error to pipe\n");  
     exit(4);  
    }  
   }  
   
   if(ferror(fp)) {  
    printf("fgets error!\n");  
    exit(5);  
   }  
   
   // close the write end  
   close(fd[1]);  
   
   if(waitpid(pid, NULL, 0) < 0) {  
    printf("waitpid error!\n");  
    exit(6);  
   }  
  } else {  
   close(fd[1]);  
   
   // duplicate the file descriptor if fd[0] is not standard input  
   // after this step, both fd[0] and STDIN_FILENO point to the same  
   // file table entry  
   if(fd[0] != STDIN_FILENO) {  
    if(dup2(fd[0], STDIN_FILENO) != STDIN_FILENO) {  
     printf("dup2 error to stdin\n");  
     exit(7);  
    }  
    close(fd[0]);  
   }  
   
   // Get the pager  
   if((pager = getenv("PAGER")) == NULL) {  
    pager = DEF_PAGER;  
   }  
   
   // Make argv0 point to the next char of last '/' in pager path  
   if((argv0 = strrchr(pager, '/')) != NULL)  
    argv0++;  
   else  
    argv0 = pager;  
   
   // Execute the pager with pipe input from parent process  
   if(execl(pager, argv0, (char*)0) < 0) {  
    printf("execl error for %s\n", pager);  
    exit(8);  
   }  
  }  
   
  exit(0);  
 }  

shell:
The program create the child process which make pipe file descriptor pointing to the standard input, and it will just make kernel give the pipe content through standard input.
So in the end the pager: /bin/more just print out the 2 lines from test1:
Hello world!
amazing world!
 ubuntu@ip-172-31-23-227:~$ ./pipe.out test1  
 Hello world!  
 amazing world!  

Unix Prog: IPC Pipe(1)

1. Pipes
In history, pipes have been half duplex: data flows in only one direction. Some systems now support full duplex. Pipes can be used only between processes that have a common ancestor.

A main area for pipe: every time we type a sequence of commands in a pipeline for the shell to execute, the shell creates a separate process for each command and links the standard output of one to the standard input of the next using a pipe.

2. Pipe system call:
System Definition:
 ubuntu@ip-172-31-23-227:~$ less /usr/include/unistd.h  
 ......  
 /* Create a one-way communication channel (pipe).  
   If successful, two file descriptors are stored in PIPEDES;  
   bytes written on PIPEDES[1] can be read from PIPEDES[0].  
   Returns 0 if successful, -1 if not. */  
 extern int pipe (int __pipedes[2]) __THROW __wur;  
 ......  

two file descriptors are returned, pipedes[0] is open for reading, pipedes[1] is open for writing.

For a pipe from the parent to the child, the parent closes the read end of the pipe(fd[0]), and the child closes the write end(fd[1]). For a pipe from the child to the parent, the parent closes fd[1] and child closes fd[0].

Following diagram illustrates this:

If we read from a pipe whose write end has been closed, read returns 0 to indicate an end of file after all the data has been read. If we write to a pipe whose read end has been closed, the signal SIGPIPE is geerated. write returns -1 with errno set to EPIPE.

The constant PIPE_BUF specifies the kernel's pipe buffer size:
 ubuntu@ip-172-31-23-227:~$ less /usr/include/linux/limits.h  
 ......  
 #define PIPE_BUF    4096  /* # bytes in atomic write to a pipe */  
 ......  
When we're writing to a pipe(or FIFO), a write of PIPE_BUF bytes or less will not be interleaved with the writes from other processes to the same pipe(or FIFO). If multiple processes are writing to a pipe(or FIFO), and if we write more than PIPE_BUF bytes, the data might be interleaved with the data from other writers.

3. Example of pipe:
pipe.c:
 #include<stdio.h>  
 #include<stdlib.h>  
 #include<unistd.h>  
   
 int main(int argc, char* argv[])  
 {  
  int n;  
  int fd[2];  
  pid_t pid;  
  char line[20];  
   
  // Build the pipe  
  if(pipe(fd) < 0) {  
   printf("pipe error!\n");  
   exit(1);  
  }  
   
  // Make the child process  
  if((pid = fork()) < 0) {  
   printf("fork error!\n");  
   exit(2);  
  } else if(pid > 0) { // parent  
   sleep(2);  
   close(fd[0]);  
   write(fd[1], "hello world!\n", 12);  
  } else {  
   close(fd[1]);  
   n = read(fd[0], line, 20);  
   printf("return size: %d\n", n);  
   write(STDOUT_FILENO, line, n);  
  }  
   
  exit(0);  
 }  

shell:
Note: Even if parent sleep for 2 seconds before closing read end and write to write end. The child process just get stuck in read system call to wait for the writing of parent process.So we can assume that file descriptors returned by pipe are blocking I/O.

 ubuntu@ip-172-31-23-227:~$ ./pipe.out  
 ubuntu@ip-172-31-23-227:~$ return size: 12  
 hello world!  

Sunday, November 9, 2014

Unix Prog: Memory-Mapped I/O

1. Memory-Mapped I/O
Memory-Mapped I/O lets us map a file on disk into a buffer in memory so that, when we fetch bytes from the buffer, the corresponding bytes of the file are read. When we store data in the buffer, the corresponding bytes are automatically written in the file.

2. mmap
System Definition:
 ubuntu@ip-172-31-23-227:~$ less /usr/include/x86_64-linux-gnu/sys/mman.h  
 ......  
 /* Map addresses starting near ADDR and extending for LEN bytes. from  
   OFFSET into the file FD describes according to PROT and FLAGS. If ADDR  
   is nonzero, it is the desired mapping address. If the MAP_FIXED bit is  
   set in FLAGS, the mapping will be at ADDR exactly (which must be  
   page-aligned); otherwise the system chooses a convenient nearby address.  
   The return value is the actual mapping address chosen or MAP_FAILED  
   for errors (in which case `errno' is set). A successful `mmap' call  
   deallocates any previous mapping for the affected region. */  
   
 #ifndef __USE_FILE_OFFSET64  
 extern void *mmap (void *__addr, size_t __len, int __prot,  
           int __flags, int __fd, __off_t __offset) __THROW;  
 ......  

mmap rule:
1) first argument addr is the address of where we want the mapped region to start. We normally set this to 0 to allow the system to choose the starting address. The return value is either starting address of the mapped area or MAP_FAILED.
2) Second argument len indicates the number of bytes to map. fd indicates the file descriptor that is to be mapped, we have to open the file before mapping. off indicates the starting offset in the file of the bytes to map.
3) Third argument prot specifies the protection of the mapped region:
 ubuntu@ip-172-31-23-227:~$ less /usr/include/x86_64-linux-gnu/bits/mman-linux.h  
 ......  
 #define PROT_READ    0x1       /* Page can be read. */  
 #define PROT_WRITE   0x2       /* Page can be written. */  
 #define PROT_EXEC    0x4       /* Page can be executed. */  
 #define PROT_NONE    0x0       /* Page can not be accessed. */  
 ......  
The protection bit is the bitwise OR combination of several bits, and it can not violate the file descriptor open mode.
4) Fourth argument flag affects various attributes of the mapped region:
 ubuntu@ip-172-31-23-227:~$ less /usr/include/x86_64-linux-gnu/bits/mman-linux.h  
 ......  
 /* Sharing types (must choose one and only one of these). */  
 #define MAP_SHARED   0x01      /* Share changes. */  
 #define MAP_PRIVATE   0x02      /* Changes are private. */  
 #ifdef __USE_MISC  
 # define MAP_TYPE    0x0f      /* Mask for type of mapping. */  
 #endif  
   
 /* Other flags. */  
 #define MAP_FIXED    0x10      /* Interpret addr exactly. */  
 ......  
MAP_FIXED: this flag indicates that the returned value must be equal to first argument addr(must be page-aligned). If this flag is not specified, mmap will not guarantee the returning address is first argument. Instead, it will try to find the correct address nearby.

MAP_SHARED: this flag indicates that once data is written to the mapped memory region, then data will be written to the file directly

MAP_PRIVATE: this flag indicates that once data is written to the mapped memory, a private copy of the mapped file is created.

5) The value of addr and offset are required to be multiples of the system's virtual memory page size, which can be obtained by sysconf function, with an argument of _SC_PAGESIZE.

6) If addr is the multiples of the system's virtual memory page size, then the mapped region must start from the beginning of some virtual memory page. In this case, if "len" is not the multiples of page size, the OS will still allocate multiples of page size to cover the entire length. For the "remaining part" in the last page, any modification will not affect the content in file.

7) When modifying the mapped region, two signals may get generated:
SIGSEGV: we have tried to access memory that is not available to us, or, we have tried to modify content in a mapped region that specified to mmap as read-only.
SIGBUS: we have tried to access part of mapped region that doesn't make sense at the time of the access. If the file is truncated to be empty, then any portion of mapped region is not making sense any more.

8) A memory-mapped region is inherited by a child across a fork, but not inherited across the exec.

3. mprotect:
We can change the permission on an existing mapping by calling mprotect:
 ubuntu@ip-172-31-23-227:~$ less /usr/include/x86_64-linux-gnu/sys/mman.h  
 .......  
 /* Change the memory protection of the region starting at ADDR and  
   extending LEN bytes to PROT. Returns 0 if successful, -1 for errors  
   (and sets errno). */  
 extern int mprotect (void *__addr, size_t __len, int __prot) __THROW;  
 ......  

Same as mmap, addr must be the multiple of virtual memory page size.

4. msync
If the pages in a shared mapping have been modified, we can call msync to flush the changes to the file that backs the mapping.
Note: If the mapping is private, the file mapped is not modified.
 ubuntu@ip-172-31-23-227:~$ less /usr/include/x86_64-linux-gnu/sys/mman.h  
 ......  
 /* Synchronize the region starting at ADDR and extending LEN bytes with the  
   file it maps. Filesystem operations on a file being mapped are  
   unpredictable before this is done. Flags are from the MS_* set.  
   
   This function is a cancellation point and therefore not marked with  
   __THROW. */  
 extern int msync (void *__addr, size_t __len, int __flags);  
 ......  

Same as above, addr must be the multiple of virtual memory page size.

The third argument, flags allows us some control over how the memory is flushed.
 ubuntu@ip-172-31-23-227:~$ less /usr/include/x86_64-linux-gnu/bits/mman-linux.h  
 ......  
 /* Flags to `msync'. */  
 #define MS_ASYNC    1        /* Sync memory asynchronously. */  
 #define MS_SYNC     4        /* Synchronous memory sync. */  
 #define MS_INVALIDATE  2        /* Invalidate the caches. */  
 ......  

MS_ASYNC will simply schedule the pages to be written and then return
MS_SYNC will make msync wait for the write to complete before returning.
MS_INVALIDTE will make operating system to discard any pages that are out of sync with the underlying storage.

4. munmap
System Definition:
 ubuntu@ip-172-31-23-227:~$ less /usr/include/x86_64-linux-gnu/sys/mman.h  
 ......  
 /* Deallocate any mapping for the region starting at ADDR and extending LEN  
   bytes. Returns 0 if successful, -1 for errors (and sets errno). */  
 extern int munmap (void *__addr, size_t __len) __THROW;  
 ......  

same as above, addr need to be the multiples of virtual memory page size.
A memory-mapped region is automatically unmapped when the process terminates or by calling munmap directly. Closing the filedes doesn't unmap the region.
munmap doesn't affect the object that was mapped, the call to munmap does not cause the contents of the mapped region to be written to the disk file.

5. Example:
map.c:
 #include<stdio.h>  
 #include<stdlib.h>  
 #include<unistd.h>  
 #include<fcntl.h>  
 #include<string.h>  
 #include<sys/mman.h>  
   
 int main(int argc, char* argv[])  
 {  
  int fdin, fdout;  
  void *src, *dst;  
  struct stat statbuf;  
   
  // Open the input file, create the output file  
  if((fdin = open(argv[1], O_RDONLY)) < 0) {  
   printf("can't open the file.\n");  
   exit(1);  
  }  
   
  if((fdout = open(argv[2], O_RDWR | O_CREAT | O_TRUNC)) < 0) {  
   printf("can't create the file for writing.\n");  
   exit(2);  
  }  
   
  // Get the input file size  
  if(fstat(fdin, &statbuf) < 0) {  
   printf("fstat error!\n");  
   exit(3);  
  }  
   
  // Setup the output file size, in order to make sure memory mapping  
  if(lseek(fdout, statbuf.st_size - 1, SEEK_SET) == -1) {  
   printf("lseek error!\n");  
   exit(4);  
  }  
   
  if(write(fdout, "", 1) != 1) {  
   printf("write error!\n");  
  }  
   
  // Setup the memory mapping for input file  
  if((src = mmap(0, statbuf.st_size, PROT_READ, MAP_SHARED, fdin, 0)) == MAP_FAILED) {  
   printf("mmap error for ouptut!\n");  
   exit(5);  
  }  
   
  // Setup the memory mapping for output file  
  if((dst = mmap(0, statbuf.st_size, PROT_READ | PROT_WRITE, MAP_PRIVATE, fdout, 0)) == MAP_FAILED) {  
   printf("mmap error for output!\n");  
   exit(5);  
  }  
   
  // Do the memory copy, note that fdout is mapped privately, so any data won't be  
  // written to the new file even if the msync is called.  
  memcpy(dst, src, statbuf.st_size);  
   
  // Unmap the output mapped region  
  munmap(dst, statbuf.st_size);  
   
  // re-establish the mapped region for output publicly(MAP_SHARED);  
  if((dst = mmap(0, statbuf.st_size, PROT_READ | PROT_WRITE, MAP_SHARED, fdout, 0)) == MAP_FAILED) {  
   printf("mmap error for output!\n");  
   exit(5);  
  }  
   
  // This time, data will be written to output file immediately after memcpy  
  memcpy(dst, src, statbuf.st_size);  
  exit(0);  
 }  

shell:
 ubuntu@ip-172-31-23-227:~$ ./map.out test1.txt test2.txt  
 ubuntu@ip-172-31-23-227:~$ cat test2.txt  
 Hello world!  
 ubuntu@ip-172-31-23-227:~$ cat test1.txt  
 Hello world!  

Note:
Memory-mapped I/O is more efficient than standard I/O. Since memory mapped I/O only transfers data among kernel buffers. Standard I/O need to copy data in kernel buffer to application buffer, then copy data from application buffer to kernel buffer: read from input file, write to output file.

Unix Prog: readn, writen

1. readn, writen
read system call may return less than asked for, even though we have not encountered the end of file.
write system call may also return less than we specified. This may be caused by flow control constraints by downstream modules.

Above issues should never happen when reading writing a disk file, except when the file system runs out of space or we hit our quota limit and we can't write all that we requested

readn, writen simply call read or write as many times a required to read or write the entire N bytes of data.

2. System Definition:
Linux seems doesn't support these two functions
Unix system definition
 ssize_t readn(int filedes, void *buff, size_t nbytes);  
 ssize_t writen(int filedes, const void *buff, size_t nbytes);  

Given file descriptor, buffer, nbytes, these two function just try as many times as they can to read/write nbytes data.

3. Sample Implementation:
vio.c:
 #include<stdio.h>  
 #include<stdlib.h>  
 #include<unistd.h>  
 #include<fcntl.h>  
   
 ssize_t readn(int fd, void *ptr, size_t n)  
 {  
  size_t nleft;  
  ssize_t nread;  
   
  nleft = n;  
  while(nleft > 0) {  
   if((nread = read(fd, ptr, nleft)) < 0) {  
    if(nleft == n)  
     return -1;  
    else  
     break;  
   } else if(nread == 0) {  
    break;  
   }  
   
   nleft -= nread;  
   ptr += nread;  
  }  
   
  return n-nleft;  
 }  
   
 ssize_t writen(int fd, const void* ptr, size_t n)  
 {  
  size_t nleft;  
  ssize_t nwritten;  
   
  nleft = n;  
  while(nleft > 0) {  
   if((nwritten = write(fd, ptr, nleft)) < 0) {  
    if(nleft == n)  
     return -1;  
    else  
     break;  
   } else if (nwritten == 0) {  
    break;  
   }  
   
   nleft -= nwritten;  
   ptr += nwritten;  
  }  
   
  return n-nleft;  
 }  
   
 int main(int argc, char* argv[])  
 {  
  int fd;  
  char buf1[10] = "Hello\n";  
  char buf2[10];  
  if((fd = open(argv[1], O_RDWR | O_CREAT)) < 0) {  
   printf("open error!\n");  
   exit(1);  
  }  
   
  writen(fd, buf1, 6);  
  lseek(fd, SEEK_SET, 0);  
  readn(fd, buf2, 6);  
   
  printf("buffer read out: %s\n", buf2);  
   
  exit(0);  
 }  

shell:
 ubuntu@ip-172-31-23-227:~$ ./vio.out test.txt  
 buffer read out: Hello