Advertisement
heavenriver

pipe.c

Nov 26th, 2013
37
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.26 KB | None | 0 0
  1. /* basic pipelining, UNIX-native */
  2.  
  3.  /* pointer arithmetics:
  4.   *
  5.   * push(pointer, v) INDICATES *(pointer++) = v
  6.   * pop(pointer) INDICATES *(--pointer)
  7.   * (*++v)[0] INDICATES (**++v)
  8.   *           INDICATES first char in v
  9.   *           INDICATES name of string/vector v
  10.   * likewise, *v[0] INDICATES **v
  11.   *       and *v[n] INDICATES **(v + n)
  12.   * returntype (*funct)(args) INDICATES a function funct with arguments args which returns...
  13.   * char **argv INDICATES pointer to char pointer
  14.   * int(*v)[len] INDICATES pointer "v" to a vector of "len" int elements
  15.   * int *v[len] INDICATES vector "v" of "len" pointers to int elements
  16.   * void *funct() INDICATES function "funct" that returns a pointer-to-void
  17.   * void (*funct)() INDICATES pointer to a function "funct" that returns void
  18.   *
  19.   */
  20.  
  21.  /* useful characters: [] # */
  22.  
  23.  # include <stdio.h>
  24.  # include <stdlib.h> // for exit
  25.  # include <sys/ipc.h>
  26.  # include <sys/shm.h> // for shmdet
  27.  # include <sys/types.h> // for shmdet
  28.  # include <string.h> // for strcpy
  29.  
  30.  # define SIZE 1024 // message size
  31.  # define exception(x) { puts(x); exit(1); }
  32.  
  33.  int main(int argc, char * argv[])
  34.     {
  35.      /* creating a FIFO queue */
  36.      char msg[SIZE];
  37.      int pid, isparent, fd[2], val; // *fd is for reading, *++fd is for writing
  38.      val = pipe(fd); // creates the pipe
  39.      // if(val == -1) exception("Pipe creation failed");
  40.      pid = fork(); // generates child process
  41.      // if(pid == -1) exception("Fork error");
  42.      /* child process: reader */
  43.      if(pid == 0)
  44.     {
  45.      close(fd[1]); // always close the buffer before starting to read!
  46.      while(read(fd[0], msg, SIZE) > 0) // reads all messages
  47.         printf(msg);
  48.      close(fd[0]); // closes the other buffer
  49.     }
  50.      /* parent process: writer */
  51.      else
  52.     {
  53.      close(fd[0]); // same consideration applies
  54.      puts("Input text to transfer (or 'quit'): ");
  55.      do {
  56.          fgets(msg, SIZE, stdin); // reads message from standard input (keyboard)
  57.          write(fd[1], msg, SIZE); // writes message
  58.          printf("Message: %s", msg); // prints message
  59.      } while(strcmp(msg, "quit\n") != 0);
  60.      close(fd[1]);
  61.      wait(&isparent); // waits for child death (end of reading)
  62.     }
  63.      /* see pg. 50 for analogous example with mkfifo() */
  64.      return 0;
  65.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement