maint.mk: Update system header list for #include syntax checks.
[gnulib.git] / tests / test-nonblocking-pipe-main.c
blob1602abb1759c1382bfc2c14404053bae75ea2c87
1 /* Test for nonblocking read and write on pipes.
3 Copyright (C) 2011-2024 Free Software Foundation, Inc.
5 This program is free software: you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation, either version 3 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program. If not, see <https://www.gnu.org/licenses/>. */
18 #include <config.h>
20 #include <errno.h>
21 #include <stdlib.h>
22 #include <string.h>
23 #include <unistd.h>
24 #include <sys/time.h>
26 #if defined _WIN32 && ! defined __CYGWIN__
27 # include <process.h>
28 #else
29 # include <spawn.h>
30 #endif
32 #include "nonblocking.h"
33 #include "wait-process.h"
35 #include "macros.h"
36 #include "test-nonblocking-pipe.h"
37 #define PROG_ROLE "main"
38 #include "test-nonblocking-writer.h"
40 int
41 main (int argc, char *argv[])
43 const char *child_path;
44 int test;
45 int fd[2];
46 pid_t child;
47 int exitcode;
49 child_path = argv[1];
50 test = atoi (argv[2]);
52 /* Create a pipe. */
53 ASSERT (pipe (fd) >= 0);
55 /* Map fd[0] to STDIN_FILENO and fd[1] to STDOUT_FILENO, because on Windows,
56 the only three file descriptors that are inherited by child processes are
57 STDIN_FILENO, STDOUT_FILENO, STDERR_FILENO. */
58 if (fd[0] != STDIN_FILENO)
60 ASSERT (dup2 (fd[0], STDIN_FILENO) >= 0);
61 close (fd[0]);
63 if (fd[1] != STDOUT_FILENO)
65 ASSERT (dup2 (fd[1], STDOUT_FILENO) >= 0);
66 close (fd[1]);
69 /* Prepare the file descriptors. */
70 if (test & 1)
71 ASSERT (set_nonblocking_flag (STDOUT_FILENO, true) >= 0);
72 if (test & 2)
73 ASSERT (set_nonblocking_flag (STDIN_FILENO, true) >= 0);
75 /* Spawn the child process. */
77 const char *child_argv[3];
79 child_argv[0] = child_path;
80 child_argv[1] = argv[2];
81 child_argv[2] = NULL;
83 #if defined _WIN32 && ! defined __CYGWIN__
84 child = _spawnvpe (P_NOWAIT, child_path, child_argv,
85 (const char **) environ);
86 ASSERT (child >= 0);
87 #else
89 pid_t child_pid;
90 int err =
91 posix_spawnp (&child_pid, child_path, NULL, NULL, (char **) child_argv,
92 environ);
93 ASSERT (err == 0);
94 child = child_pid;
96 #endif
99 /* Close unused file descriptors. */
100 close (STDIN_FILENO);
102 exitcode =
103 main_writer_loop (test, PIPE_DATA_BLOCK_SIZE, STDOUT_FILENO, false);
106 int err =
107 wait_subprocess (child, child_path, false, false, false, false, NULL);
108 ASSERT (err == 0);
111 return (exitcode ? exitcode : test_exit_status);