summaryrefslogtreecommitdiff
path: root/reference/C/EXAMPLES/pipe2.c
blob: 726c5e19b6bb07b1cefbcde4883b59a1c1f61a55 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/****************************************************************
 *
 * Purpose: Basic example of pipe. 
 *          Read and write variable length records across a pipe.
 *
 * Author:  M J Leslie
 *
 * Date:    17 Apr 96
 *
 ****************************************************************/

#include <sys/types.h>
#include <unistd.h>			/* pipe.			*/
#include <signal.h>

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);
  }
      
}