Debian Codegraph @

gcc/testsuite/gcc.dg/analyzer/pipe-glibc.c

raw
1 /* { dg-skip-if "" { "avr-*-*" } } */
2 /* { dg-require-fork "" } */
3
4 /* Example of pipe usage from glibc manual. */
5
6 #include <sys/types.h>
7 #include <unistd.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10
11 /* Read characters from the pipe and echo them to stdout. */
12
13 void
14 read_from_pipe (int file)
15 {
16 FILE *stream;
17 int c;
18 stream = fdopen (file, "r");
19 if (stream == NULL)
20 exit (EXIT_FAILURE);
21 while ((c = fgetc (stream)) != EOF)
22 putchar (c);
23 fclose (stream);
24 }
25
26 /* Write some random text to the pipe. */
27
28 void
29 write_to_pipe (int file)
30 {
31 FILE *stream;
32 stream = fdopen (file, "w");
33 if (stream == NULL)
34 exit (EXIT_FAILURE);
35 fprintf (stream, "hello, world!\n");
36 fprintf (stream, "goodbye, world!\n");
37 fclose (stream);
38 }
39
40 int
41 main (void)
42 {
43 pid_t pid;
44 int mypipe[2];
45
46 /* Create the pipe. */
47 if (pipe (mypipe))
48 {
49 fprintf (stderr, "Pipe failed.\n");
50 return EXIT_FAILURE;
51 }
52
53
54 /* Create the child process. */
55 pid = fork ();
56 if (pid == (pid_t) 0)
57 {
58 /* This is the child process.
59 Close other end first. */
60 close (mypipe[1]);
61 read_from_pipe (mypipe[0]);
62 return EXIT_SUCCESS;
63 }
64 else if (pid < (pid_t) 0)
65 {
66 /* The fork failed. */
67 fprintf (stderr, "Fork failed.\n");
68 return EXIT_FAILURE;
69 }
70 else
71 {
72 /* This is the parent process.
73 Close other end first. */
74 close (mypipe[0]);
75 write_to_pipe (mypipe[1]);
76 return EXIT_SUCCESS;
77 }
78 }