相关疑难解决方法(0)

实际例子使用dup或dup2

我知道是什么dup/dup2做什么,但我不知道什么时候会被使用.

任何实际的例子?

谢谢.

c unix file system-calls dup

63
推荐指数
4
解决办法
8万
查看次数

在 shell 中运行 cat 命令时出现错误的文件描述符

我正在尝试在我为类 Unix 操作系统 (xV6) 编写的 shell 中实现 I/O 重定向。在我为操作系统阅读的手册中,我发现以下代码将在 shell 中运行以执行 cat 命令:

char *argv[2];
argv[0] = "cat";
argv[1] = 0;
if(fork() == 0) {
    close(0);
    open("input.txt", O_RDONLY);
    exec("cat", argv);
}
Run Code Online (Sandbox Code Playgroud)

我修改了代码以在我的 shell 中运行,它的 argv 数组位于另一个函数中,但它保持了功能。出于某种原因,当我运行cat < input.txtshell 输出时:

cat: -: Bad file descriptor
cat: closing standard input: Bad file descriptor
Run Code Online (Sandbox Code Playgroud)

我还是 OS 编程的新手,所以我对 I/O 重定向的所有功能不是很清楚,但我认为我拥有的代码应该可以工作。什么可能导致问题。我有下面的 I/O 重定向代码:

case '<':
    ecmd = (struct execcmd*)cmd;
    rcmd = (struct redircmd*)cmd;

    if(fork() == 0){
      close(0);
      open("input", O_RDONLY);
      execvp(ecmd->argv[0], ecmd->argv );
    } …
Run Code Online (Sandbox Code Playgroud)

c linux operating-system xv6

2
推荐指数
1
解决办法
8091
查看次数

标签 统计

c ×2

dup ×1

file ×1

linux ×1

operating-system ×1

system-calls ×1

unix ×1

xv6 ×1