sách gpt4 ai đã đi

Không thể dup2 ghi kết thúc đường ống vào đầu ra chuẩn

In lại 作者:塔克拉玛干 更新时间:2023-11-03 01:58:13 32 4
mua khóa gpt4 Nike

我在使用 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/

32 4 0
Bài viết được đề xuất: linux - Linux 上的 rsnapshot 失败并显示 "returned 12 while processing"
Bài viết được đề xuất: C++——typedef "inside"模板参数?
Bài viết được đề xuất: linux - zmap 命令后的 Cat
Bài viết được đề xuất: c++ - 文件夹复制 VC++
Giấy chứng nhận ICP Bắc Kinh số 000000
Hợp tác quảng cáo: 1813099741@qq.com 6ren.com