C:`write error:fork、dup2和execv之后的'Bad file descriptor'
继续,但我要重申: 对于家庭作业,我必须编写一个包含重定向的基本shell。程序使用readline提示输入,解析输入字符串,并将其分解为可执行文件名、参数和输入/输出文件(如果适用)。解析字符串后,它将其和子execv分叉到传入的可执行文件。我正在使用dup2来更改fork之后和execv之前的文件描述符,但是一旦程序执行到新的可执行文件,我就遇到了一个问题。如果在shell中运行ls>foo.out,则会得到:ls:write error:Bad file descriptor 下面是我的子进程的代码,它位于fork之后:C:`write error:fork、dup2和execv之后的'Bad file descriptor',c,exec,fork,file-descriptor,C,Exec,Fork,File Descriptor,继续,但我要重申: 对于家庭作业,我必须编写一个包含重定向的基本shell。程序使用readline提示输入,解析输入字符串,并将其分解为可执行文件名、参数和输入/输出文件(如果适用)。解析字符串后,它将其和子execv分叉到传入的可执行文件。我正在使用dup2来更改fork之后和execv之前的文件描述符,但是一旦程序执行到新的可执行文件,我就遇到了一个问题。如果在shell中运行ls>foo.out,则会得到:ls:write error:Bad file descriptor 下面是我的子
int _child(struct command *c){
int ret;
/* When given `ls > foo.out`, these next two lines output:
** c->infile is (null)
** c->outfile is foo.out
*/
printf("c->infile is %s\n",c->infile);
printf("c->outfile is %s\n",c->outfile);
if(c->infile){
int fd = open( c->infile, O_RDONLY);
int _fd_dup = dup2(fd,0);
close(0);
if(_fd_dup != 0){
fprintf(stderr, "Failed to redirect command input.\n");
return 0;
}
}
if(c->outfile){
int fd = open( c->outfile, O_WRONLY | O_CREAT | O_TRUNC, 0600);
int _fd_dup = dup2(fd,1);
close(1);
if(_fd_dup != 1){
fprintf(stderr, "Failed to redirect command output.\n");
return 0;
}
}
我没有得到重定向失败的命令输出。错误正如我提到的,这是一项家庭作业,所以我不想找人来解决这个问题,而是给我指出了正确的方向。问题在于这段代码:
int _fd_dup = dup2(fd,1);
close(1);
您应该关闭fd,而不是1。在fd 0的情况下也存在同样的问题。问题出在这段代码中:
int _fd_dup = dup2(fd,1);
close(1);
您应该关闭fd,而不是1。在FD0的情况下,您也有同样的问题