lh | 9ed821d | 2023-04-07 01:36:19 -0700 | [diff] [blame] | 1 | #include <stdio.h> |
| 2 | #include <string.h> |
| 3 | #include <unistd.h> |
| 4 | |
| 5 | static int |
| 6 | do_test (void) |
| 7 | { |
| 8 | int fd = dup (fileno (stdout)); |
| 9 | if (fd <= 1) |
| 10 | { |
| 11 | puts ("dup failed"); |
| 12 | return 1; |
| 13 | } |
| 14 | |
| 15 | FILE *f1 = fdopen (fd, "w"); |
| 16 | if (f1 == NULL) |
| 17 | { |
| 18 | printf ("fdopen failed: %m\n"); |
| 19 | return 1; |
| 20 | } |
| 21 | |
| 22 | fclose (stdout); |
| 23 | |
| 24 | FILE *f2 = popen ("echo test1", "r"); |
| 25 | if (f2 == NULL) |
| 26 | { |
| 27 | fprintf (f1, "1st popen failed: %m\n"); |
| 28 | return 1; |
| 29 | } |
| 30 | FILE *f3 = popen ("echo test2", "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 (&line, &len, 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 (&line, &len, f2) != -1) |
| 52 | { |
| 53 | fputs ("second getline did not return -1\n", f1); |
| 54 | result = 1; |
| 55 | } |
| 56 | |
| 57 | if (getline (&line, &len, 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 (&line, &len, f3) != -1) |
| 69 | { |
| 70 | fputs ("second getline did not return -1\n", f1); |
| 71 | result = 1; |
| 72 | } |
| 73 | |
| 74 | int ret = pclose (f2); |
| 75 | if (ret != 0) |
| 76 | { |
| 77 | fprintf (f1, "1st pclose returned %d\n", ret); |
| 78 | result = 1; |
| 79 | } |
| 80 | |
| 81 | ret = pclose (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" |