From 7e0f021a9aec35fd8e6725e87e3313b101d26f5e Mon Sep 17 00:00:00 2001 From: Tobias Klauser Date: Sun, 27 Jan 2008 11:37:44 +0100 Subject: Initial import (2.0.2-6) --- reference/C/EXAMPLES/pipe2.c | 103 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 reference/C/EXAMPLES/pipe2.c (limited to 'reference/C/EXAMPLES/pipe2.c') diff --git a/reference/C/EXAMPLES/pipe2.c b/reference/C/EXAMPLES/pipe2.c new file mode 100644 index 0000000..726c5e1 --- /dev/null +++ b/reference/C/EXAMPLES/pipe2.c @@ -0,0 +1,103 @@ +/**************************************************************** + * + * Purpose: Basic example of pipe. + * Read and write variable length records across a pipe. + * + * Author: M J Leslie + * + * Date: 17 Apr 96 + * + ****************************************************************/ + +#include +#include /* pipe. */ +#include + +void Child (pid_t Handle); +void Parent (pid_t Handle); + +main() +{ + + pid_t Pid; + int fd[2]; + + pipe(fd); /* Create two file descriptors */ + + Pid = fork(); + + if ( Pid == 0) /* Child */ + { + close(fd[0]); + Child(fd[1]); + puts("Child end"); + } + else /* Parent */ + { + close(fd[1]); + Parent(fd[0]); + puts("Parent end"); + } +} + +/**************************************************************** + * + * The Child sends data to the parent. + * + ****************************************************************/ + +void Child(pid_t Handle) +{ + int Len; + + char Buff[50]="Bass Beer"; + + Len = strlen(Buff)+1; + write(Handle, &Len, sizeof(Len)); + write(Handle, Buff, Len); + + strcpy(Buff, "Wild times."); + Len = strlen(Buff)+1; + write(Handle, &Len, sizeof(Len)); + write(Handle, Buff, Len); + + strcpy(Buff, "Alex was ere."); + Len = strlen(Buff)+1; + write(Handle, &Len, sizeof(Len)); + write(Handle, Buff, Len); + + strcpy(Buff, "Bon Jovi rules the world."); + Len = strlen(Buff)+1; + write(Handle, &Len, sizeof(Len)); + write(Handle, Buff, Len); + + close(Handle); +} + +/**************************************************************** + * + * Read the data sent by the child. + * + ****************************************************************/ + +void Parent(pid_t Handle) +{ + + int Len; + char Buff[50]; + + /* ... Perform two reads. THe first gets the length of the data + ... the second gets the actual data. */ + + while (read(Handle, &Len, sizeof(Len)) > 0) + { + read(Handle,Buff, Len); + printf("%s\n", Buff); + } + +} + + + + + -- cgit v1.2.3-54-g00ecf