xref: /haiku/src/tests/system/libroot/posix/posix_spawn_pipe_test.c (revision 1e60bdeab63fa7a57bc9a55b032052e95a18bd2c)
1 #include "posix_spawn_pipe_test.h"
2 
3 #include <errno.h>
4 #include <unistd.h>
5 #include <spawn.h>
6 #include <stdio.h>
7 #include <string.h>
8 
9 #define panic(n, str) if (n != 0) { perror(str); return 1; }
10 #define readIdx 0
11 #define writeIdx 1
12 
13 int main() {
14   int out[2], err[2];
15   posix_spawn_file_actions_t fdops;
16   pid_t pid;
17   char* const argv[] = { "./posix_spawn_pipe_err", NULL };
18 
19   panic(pipe(out), "pipe stdout");
20   panic(pipe(err), "pipe stderr");
21 
22   errno = posix_spawn_file_actions_init(&fdops);
23   panic(errno, "init");
24   errno = posix_spawn_file_actions_addclose(&fdops, out[readIdx]);
25   panic(errno, "close stdout read");
26   errno = posix_spawn_file_actions_adddup2(&fdops, out[writeIdx], 1);
27   panic(errno, "dup2 stdout write");
28   errno = posix_spawn_file_actions_addclose(&fdops, err[readIdx]);
29   panic(errno, "close stderr read");
30   errno = posix_spawn_file_actions_adddup2(&fdops, err[writeIdx], 2);
31   panic(errno, "dup2 stderr write");
32   errno = posix_spawn(&pid, "./posix_spawn_pipe_err", &fdops, NULL, argv, NULL);
33   panic(errno, "spawn");
34 
35   FILE *cOut = fdopen(out[readIdx], "r");
36   if (cOut == NULL) panic(-1, "cOut");
37   FILE *cErr = fdopen(err[readIdx], "r");
38   if (cErr == NULL) panic(-1, "cErr");
39 
40   char *buf = NULL;
41   size_t bufsize = 0;
42   getline(&buf, &bufsize, cOut);
43   panic(ferror(cOut), "getline cOut");
44   if (strcmp(buf, testOut) != 0) {
45     printf("stdout got: %s", buf);
46     printf("stdout exp: %s", testOut);
47   }
48   getline(&buf, &bufsize, cErr);
49   panic(ferror(cErr), "getline cErr");
50   if (strcmp(buf, testErr) != 0) {
51     printf("stderr got: %s", buf);
52     printf("stderr exp: %s", testErr);
53   }
54 
55   return 0;
56 }
57