Bài viết phổ biến của tác giả
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我在使用 dup2() 和 pipe() 时遇到问题。
当我尝试将管道的写入端 dup2 到 STDOUT_FILENO 时,我收到了 EBADF。
我用 gdb 在 dup2(pout[1], STDOUT_FILENO)
上中断并检查了 /proc/$pid/fdinfo/$pout[1]
有 O_WRONLY旗帜。这个麻烦快把我逼疯了。
NOTES:
- at the start of the function i initialize all pipes to -1.
- this issue happens only on x86, on my x86_64 workstation everything goes fine.
- OS is Gentoo GNU/Linux ( both x86 and x86_64 machines )
if(pipe2(pexec, O_CLOEXEC)) {
fprintf(stderr, "%s: exec pipe: %s\n", __func__, strerror(errno));
goto start_fail;
}
if(h->have_stdin && pipe(pin)) {
fprintf(stderr, "%s: input pipe: %s\n", __func__, strerror(errno));
goto start_fail;
}
if(h->have_stdout && pipe(pout)) {
fprintf(stderr, "%s: output pipe: %s\n", __func__, strerror(errno));
goto start_fail;
}
if(h->have_stdout) {
printf("%s: output pipes: rd=%d wr=%d\n", __func__, pout[0], pout[1]);
}
if((pid = fork()) < 0) {
fprintf(stderr, "%s: fork: %s\n", __func__, strerror(errno));
goto start_fail;
} else if(!pid) {
// child
close(pexec[0]);
close(pin[1]);
close(pout[0]);
i= open("/dev/null", O_RDWR);
if(pin[0] == -1)
pin[0] = i;
if(pout[1] == -1)
pout[1] = i;
if(h->workdir)
chdir(h->workdir);
if(dup2(pin[0], STDIN_FILENO)) {
fprintf(stderr, "%s: dup2(%d, %d): %s\n", __func__, pin[0], STDIN_FILENO, strerror(errno));
}
if(dup2(pout[1], STDOUT_FILENO)) {
fprintf(stderr, "%s: dup2(%d, %d): %s\n", __func__, pout[1], STDOUT_FILENO, strerror(errno));
}
#ifdef NDEBUG
dup2(i, STDERR_FILENO);
#kết thúc nếu
close(i);
close(pin[0]);
close(pout[1]);
execv(argv[0], argv);
fprintf(stderr, "%s: execv: %s\n", __func__, strerror(errno));
write(pexec[1], "!", 1);
close(pexec[1]);
exit(-1);
} khác {
// parent
close(pexec[1]);
close(pin[0]);
close(pout[1]);
if(read(pexec[0],&exec_failed, 1)) {
fprintf(stderr, "%s: exec failed\n", __func__);
waitpid(pid, NULL, 0);
goto start_fail;
}
#ifndef NDEBUG
printf("%s: successfully started command '%s' (pid=%d)\n", __func__, argv[0], pid);
#kết thúc nếu
close(pexec[0]);
}
输出如下:
...
handle_cmd_start: output pipes: rd=12 wr=13
...
...
handle_cmd_start: dup2(13, 1): Bad file descriptor
handle_cmd_start: successfully started command 'tools/nmap/nmap' (pid=1154)
....
在此先感谢您的帮助。
1 Câu trả lời
dup2
成功时返回目标文件描述符,而不是零。你的支票不应该是 if (dup2(...))
Nhưngif (dup2(...) < 0)
.
关于不能 dup2 将管道的末端写入标准输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25722730/
我正在尝试将 View 的背景设置为具有从 Palette api 生成颜色的渐变 渐变将从纯色逐渐淡出,但我希望纯色部分占据大部分背景。现在它开始稳定,然后在 View 宽度上逐渐淡出,我希望它从
Tôi là một lập trình viên xuất sắc, rất giỏi!