问题描述
我正在尝试将输出从ls
重定向到文件,该文件在C语言中创建的外壳中.我键入:
I am trying to redirect the output from ls
to a file, in a shell I created in C. I type in:
ls > junk
我得到的是:
ls: cannot access >: No such file or directory
然后,如果我使用CTRL-D退出外壳程序,则会在退出之前将ls命令的结果打印到屏幕上.我试图使用打印语句找出发生的地方,并且在以下情况下没有打印打印语句:
Then if I use CTRL-D to exit the shell it prints the results of the ls command to the screen before exiting. I tried to use print statements to figure out where it is happening and no print statements get printed after:
dup2(f, STDOUT_FILENO); Also tried dup2(f, 1);
代码:
pid = fork();
if(pid == 0)
{
// Get the arguments for execvp into a null terminated array
for(i = 0; i <= count; i++)
{ if(i == count)
{
args[i] = (char *)malloc(2 * sizeof(char));
args[i] = '\0';
}
else
{
str = strlen(string[i]);
args[i] = malloc(str);
strcpy(args[i], string[i]);
}
}
if(count == 1)
{
}
else if(strcmp(string[(numargs + 1)], ">") == 0) //numargs is the number of arguments typed in by the user
{
// printed out string[numargs+2] previously, and it says junk
int f = open(string[(numargs + 2)], O_WRONLY | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
if(f < 0)
{
printf("Unable to open output file\n");
status = 1;
}
else
{
fflush(stdout);
dup2(f, STDOUT_FILENO);
close(f);
}
}
j = execvp(string[0], args); // The first element of the string array is the first thing the user enters which is the command ls in this case
称为垃圾文件的文件已创建,但放置在其中的所有文件均为垃圾文件.我已经为此苦苦挣扎了一段时间,因此对弄清为什么重定向不起作用的任何帮助将不胜感激.谢谢.
The file called junk gets created, but all that gets placed in it is junk. I have been struggling with this for a while so any help figuring out why the redirection won't work would be greatly appreciated. Thanks.
推荐答案
您不能使用execvp
来解析shell命令.
You cannot use execvp
to parse shell commands.
shell可以识别重定向(>)字符(例如bash
,sh
,ksh
),并且execvp
执行直接传递该命令的命令.它不会尝试解释参数并创建文件重定向等.
The redirection (>) character is understood by the shell (e.g., bash
, sh
, ksh
) and execvp
executes the command you pass it directly. It does not try and interpret the arguments and create file redirections, etc.
如果要执行此操作,则需要使用system
调用.参见系统(3)
If you want to do that you need to use the system
call. See System(3)
类似地,任何其他特殊的shell字符(竖线,* 、?和&等)都将无效.
Similarly, any other special shell characters (pipe, *, ?, &, etc) won't work.
这篇关于使用execvp在输出重定向期间接收错误代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!