Cover V02, I04
Article
Listing 1
Listing 2
Listing 3
Sidebar 1

jul93.tar


Listing 3: Writing to the pipe example

1  /* Listing 3
2   * Writing to the   pipe example
3   */
4  #include <stdio.h>
5
6  main()
7  {
8  static char *slines[] =
9      {
10      "This is the first line of the example",
11      "and this is the second line",
12      "and of course this is the third"
13      };
14  char *com_str="cat > ascii.file";
15
16  run_wpipe(slines,   3, com_str);
17  }
18  /*
19  *   This function:
20  *   1) creates a pipe.
21  *   2) creates another process with fork().
22  *   3) couples standard input to the reading end of the pipe
23  *      using the dup() call.
24  *   4) closes file descriptors.
25  *   5) executes the child process.
26  *   6) closes the read side of the pipe.
27  *   7) opens the write side of the pipe using fdopen().
28  *   8) writes the number of input lines.
29  *   9) closes the file pointer.
30  *
31  *   lineptr is an array-of-pointers where each element is a string
32  *   to be written to the pipe.
33  */
34  int run_wpipe(lineptr, nolines, exe_str)
35  char *lineptr[]; /*array-of-pointers to strings */
36  int  nolines;    /*number of lines to write */
37  char *exe_str;   /*pipe command  */
38  {
39  int i, p[2], pid;
40  FILE *ptr, *fdopen();
41
42  if(pipe(p) < 0)
43       fatal("pipe call");
44
45  switch(pid=fork())
46       {
47       case -1:
48          fatal("fork call in run_wpipe");
49       case 0:
50          close(0);    /*close the standard input */
51          dup(p[0]);   /*read side of the pipe */
52          close(p[0]); /*save the file descriptors */
53          close(p[1]);
54          execlp("/bin/sh", "sh", "-c", exe_str, NULL);
55          fatal("exec call in run_wpipe");
56        }
57  close(p[0]);  /*close the read side of the parent */
58  if((ptr=fdopen(p[1],"w")), ptr ==   NULL)
59       fatal("fdopen call in run_wpipe");
60
61  for(i = 0; i<nolines; i++)
62       fprintf(ptr,"%s\n", lineptr[i]);
63  fclose(ptr);
64  /*wait for child process to finish*/
65  while(wait((int *)0) != pid)
66       ;
67  }
/* End of File */