【问题标题】:Bad File Descriptor - Dual I/O redirection错误的文件描述符 - 双 I/O 重定向
【发布时间】:2015-10-08 01:21:39
【问题描述】:

我有一个家庭作业,要求我实现自己的 Linux shell。其中一部分要求我实现在同一命令中重定向输入和输出重定向的功能。

我在尝试运行排序 “文件名”时收到“排序:读取失败:-:文件描述符错误”错误。任何帮助表示赞赏!

int dualRedirect(char *toks[], string uCommand) {
int stats;
int fd;
int fd1;
int size;
vector<string> file;
string inFileName;
string outFileName;
string buffer;
int stdIn = dup(0);
int stdOut = dup(1);

stringstream stream(uCommand);

// Convert the command string to a vector
while (stream >> buffer)
    file.push_back(buffer);

// Identify the size of the vector in order to identify the output filename
size = file.size();

outFileName = toks[size - 1];

// Find "<" in order to find the input filename, then set it to NULL in order 
// to pass the appropriate args to the exec command
for (int ii = 0; toks[ii] != NULL; ii++) {
    if (!strcmp(toks[ii], "<")) {
        inFileName = toks[ii + 1];
        toks[ii] = NULL;
    }
}

// Open the input file and assign it to the fd variable
if ((fd = open(inFileName.c_str(), O_CREAT | O_WRONLY )) == -1) {
    cerr << strerror(errno);
    return 1;
}

// Set STDIN to the fd variable (redirect stdin to fd)
if (dup2(fd, STDIN_FILENO) == -1) {
    return 1;
}

// Open the output filename and assign it to fd1
if ((fd1 = open(outFileName.c_str(), O_CREAT | O_WRONLY )) == -1) {
    cerr << strerror(errno);
    return 1;
}

// Set STDOUT to the fd1 variable (redirect stdout to fd1)
if (dup2(fd1, 1) == -1) {
    cerr << strerror(errno);
    return 1;
}

// Close the original fd file
if (close(fd) == -1) {
    cerr << strerror(errno);
    return 1;
}

// Close the original fd1 file
if (close(fd1) == -1) {
    cerr << strerror(errno);
    return 1;
}

// fork and execute, passing the command and args to exec.
if (fork()) {
    waitpid(-1, &stats, NULL);
}
else {
    execvp(toks[0], toks);
    exit(-1);
}

// Restore the stdin and stdout file descriptors to their original values
dup2(stdIn, 0);
dup2(stdOut, 1);

return 1; }

【问题讨论】:

  • 你为什么在 input 文件中使用O_CREATO_WRONLY
  • 你为什么不找&gt;来设置outFileName
  • @Barmar 我错误地使用它,以便它以只读方式打开它。 O_CREAT 是复制/粘贴错误。
  • 输入文件应该是O_RDONLY
  • @Barmar 在这种情况下,outFileName 应该是字符串的 size-1。

标签: c++ shell stdout stdin dup2


【解决方案1】:

改变

if ((fd = open(inFileName.c_str(), O_CREAT | O_WRONLY )) == -1) {

到:

if ((fd = open(inFileName.c_str(), O_RDONLY )) == -1) {

“错误文件描述符”错误的原因之一是尝试从未打开以供读取的描述符中读取。

【讨论】:

  • 成功了。我知道这是我忽略的东西。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-26
  • 2011-09-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多