This is the mail archive of the cygwin mailing list for the Cygwin project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

freopen/fread/popen bug


I'm not sure exactly where the bug is, but here's what happens (STC at the end):

1. I use freopen to open a file "foo" and associate it with stdin.

2. I use fread to read a byte from foo.

3. I call popen, expecting the child process to have foo as its stdin, with the file-position indicator pointing to the second byte. But instead the child sees an empty stdin.

If I omit step 2, the child process does indeed have foo as its stdin. Are my expectations wrong, or is this a bug?

Ken

STC:

$ cat foo
Contents of foo

$ cat good.c
#include <stdio.h>
#include <string.h>
#include <errno.h>

int
main ()
{
  FILE *f;
  int nread;
  char data[100];
  char *filename = "foo";

  f = freopen (filename, "r", stdin);
  if (!f)
    {
      fprintf (stderr, "Can't freopen %s: %s\n", filename, strerror (errno));
      return 1;
    }
  f = popen ("cat", "r");
  if (!f)
    {
      fprintf (stderr, "popen failed: %s\n", strerror (errno));
      return 1;
    }
  nread = fread (data, 1, 50, f);
  if (nread < 1)
    {
      fprintf (stderr, "Nothing read.\n");
      return 1;
    }
  data[nread] = '\0';
  printf ("%s", data);
  return 0;
}

$ gcc good.c -o good

$ ./good.exe
Contents of foo

[As expected.]

$ cat bad.c
#include <stdio.h>
#include <string.h>
#include <errno.h>

int
main ()
{
  FILE *f, *g;
  int nread;
  char data[100];
  char *filename = "foo";

  f = freopen (filename, "r", stdin);
  if (!f)
    {
      fprintf (stderr, "Can't freopen %s: %s\n", filename, strerror (errno));
      return 1;
    }
  nread = fread (data, 1, 1, f);
  if (nread != 1)
    {
      fprintf (stderr, "fread failed\n");
      return 1;
    }
  g = popen ("cat", "r");
  if (!g)
    {
      fprintf (stderr, "popen failed: %s\n", strerror (errno));
      return 1;
    }
  nread = fread (data, 1, 50, g);
  if (nread < 1)
    {
      fprintf (stderr, "Nothing read.\n");
      return 1;
    }
  data[nread] = '\0';
  printf ("%s", data);
  return 0;
}

$ gcc bad.c -o bad

$ ./bad.exe
Nothing read.

[Bug?]

--
Problem reports:       http://cygwin.com/problems.html
FAQ:                   http://cygwin.com/faq/
Documentation:         http://cygwin.com/docs.html
Unsubscribe info:      http://cygwin.com/ml/#unsubscribe-simple


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]