Advertisement
heavenriver

redir.c

Nov 30th, 2013
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.86 KB | None | 0 0
  1. /* exercise on UNIX file system */
  2.  /* useful characters: [] # */
  3.  
  4.  # include <stdio.h>
  5.  # include <string.h>
  6.  # include <fcntl.h> // for bitflags
  7.  # include <stdlib.h> // for exit()
  8.  
  9.  # define errormsg(x) { puts(x); exit(1); }
  10.  
  11.  int main(int argc, char * argv[])
  12.     {
  13.      // checking proper input format
  14.      if(argc != 2) errormsg("Error: Invalid input length");
  15.      
  16.      // opening (and then closing) file
  17.      int file = open(*(argv + 1), O_CREAT|O_TRUNC|O_WRONLY);
  18.      if(file == -1) errormsg("Error: Incorrect file name");
  19.      close(1); // closes stdout, why?
  20.      dup(file); // why duplicate?
  21.      
  22.      // fork
  23.      int pid, status;
  24.      pid = fork();
  25.      if(pid != 0)
  26.     wait(&status); // waits for the child process
  27.      execve("./writer", NULL, NULL); // calls the writer function
  28.      errormsg("Error: execve() call failed");
  29.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement