summaryrefslogtreecommitdiff
path: root/src/test-pipe.c
blob: 2e3d144149af7674ddc13f860b51fece9121a558 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/* Test of create_pipe_bidi/wait_subprocess.
   Copyright (C) 2009 Free Software Foundation, Inc.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software Foundation,
   Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.  */

#include <config.h>

#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include <error.h>
#include <pipe.h>
#include <wait-process.h>

const char* program_name = NULL;

static void
xfclose (FILE *ptr)
{
  if (!ptr)
    return;

  if (ferror (ptr))
    error (EXIT_FAILURE, 0, "I/O error");

  if (fclose (ptr))
    error (EXIT_FAILURE, errno, "fclose");
}

static void
test_pipe (void)
{
  int fd[2];
  char const *argv[9];
  pid_t pid;
  char buf[BUFSIZ];

  /* Set up child.  */
  {
    int i = 0;
    char const *p = getenv ("M4");
    char const *m4 = p ? p : "m4";
    argv[i++] = m4;
    argv[i++] = NULL;
    assert (i <= sizeof argv / sizeof *argv);
  }
  pid = create_pipe_bidi(argv[0], argv[0], (char **) argv,
                         false, true, true, fd);
  if (pid < 0)
    error (EXIT_FAILURE, errno, "create_pipe_bidi");

  /* Push child's input.  */
  {
    FILE *out = fdopen (fd[1], "w");
    if (! out)
      error (EXIT_FAILURE, errno, "fdopen");
    fprintf (out, "define(`a', `b')dnl\n");
    fprintf (out, "define(`b', `c')dnl\n");
    fprintf (out, "a\n");
    xfclose (out);
  }

  /* Get child's output.  */
  {
    FILE* in = fdopen (fd[0], "r");
    if (! in)
      error (EXIT_FAILURE, errno, "fdopen");
    if (!fgets (buf, sizeof buf, in))
      error (EXIT_FAILURE, 0, "fgets");
    xfclose (in);
  }

  /* Wait for child.  */
  wait_subprocess (pid, argv[0], true, false, false, true, 0);

  /* Check the result.  */
  assert (! strcmp (buf, "c\n"));
}

int
main (int argc, const char *argv[])
{
  program_name = argv[0];
  test_pipe ();
  return 0;
}