[英]dup return error (c programming in linux)
我正在嘗試創建一個簡單的程序來模擬終端中的“ ls -l | tail -n 2”調用。 我正在為此目的使用“ fork”和“ execvp”。 好吧,這是代碼:
int main(int argc, char *argv[])
{
int pipefd[2];
pid_t child1;
pid_t child2;
char* com1[] = {"ls", "-l",NULL};
char* com2[] = {"tail", "-n","2",NULL};
if (!(child1 = fork()))
{
close(STDOUT);
dup(pipefd[1]);
close(pipefd[1]);
execvp (com1[0], com1);
_exit(EXIT_SUCCESS);
}
else
{
close(pipefd[1]);
if (!(child2 = fork()))
{
close(STDIN);
dup(pipefd[0]); /* dupWR now holds the lowest fd available, meaning STDOUT's */
perror("dup 2");
close(pipefd[0]); /* reader will see EOF */
execvp (com2[0], com2);
_exit(EXIT_SUCCESS);
}
else
{
close(pipefd[0]);
waitpid(child2,0,0);
}
waitpid(child1,0,0);
}
return 0;
}
我得到這些錯誤:
dup 2: Bad file descriptor
tail: cannot fstat `standard input': Bad file descriptor
tail: -: Bad file descriptor
在我看來,同步存在問題。 實際上,如果我聲明:com2 [] = {“ ls”,“ -l”,NULL}; 它工作正常(我的意思是在普通shell中)。 此外,我發現第二個“ fork”中的第二個“ dup”返回錯誤。 這是為什么? 我不知道這段代碼在哪里。 請幫忙!
編輯:我添加了以下代碼(忘記創建管道):
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
謝謝,沒用!
close(STDOUT);
dup(pipefd[1]);
close(pipefd[1]);
由於dup
返回新的文件描述符,並且您不使用返回值,因此將其丟棄。
您是否要像這樣替換stdout?
dup2(pipefd[1], STDOUT_FILENO);
如果是這樣, pipefd[]
應該首先真正被初始化。 您的意思是叫pipe
的地方?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.