0

I meet a very string problem about dup2 and multiple thread, the code is like this:

pipe out, err;
int forkpid = fork();

if (forkpid == 0) {
    dup2(out.writeFd, STDOUT_FILENO);
    dup2(err.writeFd, STDERR_FILENO);
    printf("hello\n");
}

do {
    int res = poll(&fds, 2, 200);
    if (res) {
        for (int i = 0; i < 2; i++) {
            bytes = read(fds[i].fd, buff, size);
            if (fds[i].fd == out.readFd)
                printf("out\n");
            if (fds[i].fd == err.readFd)
                printf("err\n");
        }
    }
} while(....);

I have tested the code in a separated project, I can see "hello" is output from std, but once I put it in a big project, "hello" is output from err:(

I am using xcode5.0 and mix c++ and objective c. any idea about this? thanks

Bryan Chen
  • 45,816
  • 18
  • 112
  • 143
Jet
  • 129
  • 1
  • 8
  • Can you boil this down into a [short, self-contained, correct, compileable example](http://sscce.org/) that demonstrates your problem? – Adam Rosenfield Dec 18 '13 at 01:28
  • @AdamRosenfield, the original code is a huge project and actually I have tried this code in a very some Xcode project, it works fine. oh...Right, I just tried this: write(STDOUT_FILENO, "hello", 5); it does write to stdout, which means something has changed the printf output to stderr... – Jet Dec 18 '13 at 01:41
  • This may seem like a strange question, but is it possible that `err.writeFd` or `out.writeFd` end up being 0, 1 or 2 for some reason? You might check this with some debugging statements in your code. – Joe Z Dec 18 '13 at 03:04
  • @JoeZ, I have found the reason. I implemented a printf with NSlogV before, and I forgot that. NSlogV default seems to output info to stderr. so that's reason. – Jet Dec 23 '13 at 04:09

1 Answers1

0

I have found the reason. I implemented a printf with NSlogV before, and I forgot that. NSlogV default seems to output info to stderr. so that's reason. – Jet

Armali
  • 18,255
  • 14
  • 57
  • 171