gpt4 book ai didi

c++ - 错误的文件描述符 - 双 I/O 重定向

转载 作者:行者123 更新时间:2023-11-30 05:37:58 24 4
gpt4 key购买 nike

我的家庭作业要求我实现自己的 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; }

最佳答案

改变

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

到:

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

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

关于c++ - 错误的文件描述符 - 双 I/O 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33005084/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com