Bad File Descriptor — Двойное перенаправление ввода / вывода

У меня есть домашнее задание, которое требует, чтобы я реализовал свою собственную оболочку Linux. Часть этого требует, чтобы я реализовал функциональность для перенаправления ввода и вывода в одной команде.

Я получаю сообщение об ошибке «Сортировка: чтение не удалось: -: неверный дескриптор файла» при попытке выполнить сортировку < «имя файла»> «имя файла». Любая помощь приветствуется!

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; }

1

Решение

+ Изменить

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

чтобы:

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

Одной из причин ошибки «Bad file descriptor» является попытка чтения из дескриптора, который не открыт для чтения.

1

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector