我遇到了一个关于 dup2 和多线程的非常字符串的问题,代码是这样的:
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(....);
我已经在一个单独的项目中测试了代码,我可以看到“hello”是从 std 输出的,但是一旦我把它放在一个大项目中,“hello”就是从 err 输出的:(
我正在使用 xcode5.0 并混合 c++ 和目标 c。有什么想法吗?谢谢