1#include <stdio.h>
2#include <string.h>
3#include <unistd.h>
4
5static int
6do_test (void)
7{
8 int fd = dup (fd: fileno (stdout));
9 if (fd <= 1)
10 {
11 puts (s: "dup failed");
12 return 1;
13 }
14
15 FILE *f1 = fdopen (fd, "w");
16 if (f1 == NULL)
17 {
18 printf (format: "fdopen failed: %m\n");
19 return 1;
20 }
21
22 fclose (stdout);
23
24 FILE *f2 = popen (command: "echo test1", modes: "r");
25 if (f2 == NULL)
26 {
27 fprintf (f1, "1st popen failed: %m\n");
28 return 1;
29 }
30 FILE *f3 = popen (command: "echo test2", modes: "r");
31 if (f2 == NULL || f3 == NULL)
32 {
33 fprintf (f1, "2nd popen failed: %m\n");
34 return 1;
35 }
36
37 char *line = NULL;
38 size_t len = 0;
39 int result = 0;
40 if (getline (lineptr: &line, n: &len, stream: f2) != 6)
41 {
42 fputs ("could not read line from 1st popen\n", f1);
43 result = 1;
44 }
45 else if (strcmp (line, "test1\n") != 0)
46 {
47 fprintf (f1, "read \"%s\"\n", line);
48 result = 1;
49 }
50
51 if (getline (lineptr: &line, n: &len, stream: f2) != -1)
52 {
53 fputs ("second getline did not return -1\n", f1);
54 result = 1;
55 }
56
57 if (getline (lineptr: &line, n: &len, stream: f3) != 6)
58 {
59 fputs ("could not read line from 2nd popen\n", f1);
60 result = 1;
61 }
62 else if (strcmp (line, "test2\n") != 0)
63 {
64 fprintf (f1, "read \"%s\"\n", line);
65 result = 1;
66 }
67
68 if (getline (lineptr: &line, n: &len, stream: f3) != -1)
69 {
70 fputs ("second getline did not return -1\n", f1);
71 result = 1;
72 }
73
74 int ret = pclose (stream: f2);
75 if (ret != 0)
76 {
77 fprintf (f1, "1st pclose returned %d\n", ret);
78 result = 1;
79 }
80
81 ret = pclose (stream: f3);
82 if (ret != 0)
83 {
84 fprintf (f1, "2nd pclose returned %d\n", ret);
85 result = 1;
86 }
87
88 return result;
89}
90
91#define TEST_FUNCTION do_test ()
92#include "../test-skeleton.c"
93

source code of glibc/stdio-common/tst-popen2.c