Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* basic pipelining, UNIX-native */
- /* pointer arithmetics:
- *
- * push(pointer, v) INDICATES *(pointer++) = v
- * pop(pointer) INDICATES *(--pointer)
- * (*++v)[0] INDICATES (**++v)
- * INDICATES first char in v
- * INDICATES name of string/vector v
- * likewise, *v[0] INDICATES **v
- * and *v[n] INDICATES **(v + n)
- * returntype (*funct)(args) INDICATES a function funct with arguments args which returns...
- * char **argv INDICATES pointer to char pointer
- * int(*v)[len] INDICATES pointer "v" to a vector of "len" int elements
- * int *v[len] INDICATES vector "v" of "len" pointers to int elements
- * void *funct() INDICATES function "funct" that returns a pointer-to-void
- * void (*funct)() INDICATES pointer to a function "funct" that returns void
- *
- */
- /* useful characters: [] # */
- # include <stdio.h>
- # include <stdlib.h> // for exit
- # include <sys/ipc.h>
- # include <sys/shm.h> // for shmdet
- # include <sys/types.h> // for shmdet
- # include <string.h> // for strcpy
- # define SIZE 1024 // message size
- # define exception(x) { puts(x); exit(1); }
- int main(int argc, char * argv[])
- {
- /* creating a FIFO queue */
- char msg[SIZE];
- int pid, isparent, fd[2], val; // *fd is for reading, *++fd is for writing
- val = pipe(fd); // creates the pipe
- // if(val == -1) exception("Pipe creation failed");
- pid = fork(); // generates child process
- // if(pid == -1) exception("Fork error");
- /* child process: reader */
- if(pid == 0)
- {
- close(fd[1]); // always close the buffer before starting to read!
- while(read(fd[0], msg, SIZE) > 0) // reads all messages
- printf(msg);
- close(fd[0]); // closes the other buffer
- }
- /* parent process: writer */
- else
- {
- close(fd[0]); // same consideration applies
- puts("Input text to transfer (or 'quit'): ");
- do {
- fgets(msg, SIZE, stdin); // reads message from standard input (keyboard)
- write(fd[1], msg, SIZE); // writes message
- printf("Message: %s", msg); // prints message
- } while(strcmp(msg, "quit\n") != 0);
- close(fd[1]);
- wait(&isparent); // waits for child death (end of reading)
- }
- /* see pg. 50 for analogous example with mkfifo() */
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement