Сбой программы в процессе разветвления с трубами
Я пишу основную оболочку для домашней работы курса, которая найдет команду в заданном списке путей и выполнит команду. Он также предназначен для обработки труб. Однако, когда я разветвляю дочерний процесс, я получаю сообщение "Ошибка записи: Broken Pipe" в gdb, и программа внезапно завершается.
Кажется, я не могу понять, почему это происходит, поскольку я осторожно относился к открытию и закрытию правильных каналов, и процесс разветвления, кажется, работает как хотелось бы. Может кто-то с большим опытом программирования на C и Unix, пожалуйста, помогите мне диагностировать проблему? Есть ли что-то логически неправильное с моей реализацией fork / pipe?
//commands is of the format {"ls -al", "more", NULL}
//it represents commands connected by pipes, ex. ls -al | more
char **commands = parseArgv(consoleinput, SPECIAL_CHARS[4]);
int numcommands = 0;
while( commands[numcommands]!=NULL )
{
numcommands++;
}
const int numpipes = 2*(numcommands-1);
int pipefds[numpipes];
int i=0;
for(i=0; i<numpipes;i=i+2)
{
pipe(pipefds+i);
}
int pipe_w = 1;
int pipe_r = pipe_w - 3;
int curcommand = 0;
while(curcommand < numcommands)
{
if(pipe_w < numpipes)
{
//open write end
dup2(pipefds[pipe_w], 1);
}
if(pipe_r > 0)
{
//open read end
dup2(pipefds[pipe_r], 0);
}
for(i=0;i<numpipes;i++) //close off all pipes
{
close(pipefds[i]);
}
//Parse current command and Arguments into format needed by execv
char **argv = parseArgv(commands[curcommand], SPECIAL_CHARS[0]);
//findpath() replaces argv[0], i.e. command name by its full path ex. ls by /bin/ls
if(findPath(argv) == 0)
{
int child_pid = fork();
//Program crashes after this point
//Reason: /bin/ls: write error, broken pipe
if(child_pid < 0)
{
perror("fork error:");
}
else if(child_pid == 0) //fork success
{
if(execv(argv[0], argv) == -1)
{
perror("Bad command or filename:");
}
}
else
{
int child_status;
child_pid = waitpid(child_pid, &child_status, 0);
if(child_pid < 0)
{
perror("waitpid error:");
}
}
}
else
{
printf("Bad command or filename");
}
free(argv);
curcommand++;
pipe_w = pipe_w + 2;
pipe_r = pipe_r + 2;
}
//int i=0;
for(i=0;i<numpipes;i++) //close off all pipes
{
close(pipefds[i]);
}
free(commands);
1 ответ
Дублирование файловых дескрипторов после вызова fork(), т.е. в дочернем процессе, является правильным способом. Кроме того, вызов waitpid() заставляет один дочерний процесс ожидать другого, и оболочка зависает. Вызов wait() должен быть перемещен после цикла, то есть родитель должен ожидать всех потомков.