gpt4 book ai didi

c++ - Linux shell模拟: stuck on multiple pipes

转载 作者:太空狗 更新时间:2023-10-29 12:05:59 25 4
gpt4 key购买 nike

我知道已经有人问过类似的问题,但没有一个回复对我有帮助。我正在尝试实现一个微型 Linux shell,但卡在了多个管道上。使用单个管道的命令(例如 ls | wc)可以工作,但如果我添加第二个管道,控制台上不会显示任何内容。这是我的代码。

void ExecuteCommand(NODE *cHead,NODE *oHead)
{
int fd[10][2]; // file descriptors' array
int nfdCnt = 0 ; // file descriptors counter
string strCmd; // command
string strOp = ""; // operator
int nOpCnt = 0 ; // operator count

while(1)
{
if (cHead != NULL) // cHead is head pointer to the linked list of commands.
{
strCmd = GetCmdOROperator(&cHead); // get command
}
if (oHead == NULL) // oHead is head pointer to the linked list of operators.
{
strOp = "";
}
else
{
strOp = GetCmdOROperator(&oHead); // get operator
}

if (strOp.empty()) // no operator exists. single or last command in the chain.
{
// Fork the child process
pid_t child_id = fork();

if(child_id == 0)
{
// Execute the command

if (nOpCnt) // if we previously encountered any operator
{
close(fd[nfdCnt-1][FD_WRITE]);
dup2(fd[nfdCnt-1][FD_READ], FD_READ); // read from pipe updated by previous command
}

// call execvp()

exit(-1);
}
else
{
for (int i = 0 ; i < nfdCnt; i++)
{
close(fd[nfdCnt][0]);
close(fd[nfdCnt][1]);
}
wait(NULL);
break;
}
}

if (strOp == "|")
{
nOpCnt++ ;

if (pipe (fd[nfdCnt]) < 0)
{
printf("\npipe error");
return ;
}

pid_t child_id = fork();
if (child_id == 0)
{
close(fd[nfdCnt][FD_READ]); // we dont need this
dup2(fd[nfdCnt][FD_WRITE], FD_WRITE);

if(nOpCnt > 1) // if we have already encountered a pipe before
{
dup2(fd[nfdCnt-1][FD_READ],FD_READ);
close(fd[nfdCnt-1][FD_WRITE]);
}

// call execvp()
exit (-1);
}
else
{
nfdCnt++;
}

}

}
}

最佳答案

我没有仔细查看你的代码,但看起来你让文件描述符保持打开状态,在这种情况下进程将阻塞读取,因为即使你认为你已经关闭它,但有人打开了写入端.尝试在每个 dup2 之后添加一个关闭:

 dup2( fd[ nfdCnt - 1 ][ FD_READ ], FD_READ );
close( fd[ nfdCnt - 1 ][ FD_READ ])

(另外,添加一些错误检查。dup2forkclose等都可以失败。有时跳过也方便将问题发布到论坛时进行错误检查,但请确保在实际代码中不要忽略它。)

关于c++ - Linux shell模拟: stuck on multiple pipes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12326457/

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