我的代码中的execvp有一些问题,我想写一个简单的终端,将命令的结果保存在日志文件中,问题是当我使用"> a.log"
时,它没有响应并出错!
int lsh_launch(char **args)
{
pid_t pid;
int status;
int i = 0;
while (args[i] != NULL)
{
printf("%sn", args[i]);
i++;
}
args[i] = ">";
args[i + 1] = "a.log";
pid = fork();
if (pid == 0)
{
printf("child procn");
// Child process
if (execvp(args[0], args) == -1)
{
perror("lsh");
}
if (execvp(args[0], args) == -1)
{
perror("lsh");
}
exit(EXIT_FAILURE);
}
else if (pid < 0)
{
// Error forking
perror("lsh");
}
else
{
// Parent process
do {
waitpid(pid, &status, WUNTRACED);
} while (!WIFEXITED(status) && !WIFSIGNALED(status));
}
return 1;
}
当我用其他值更改参数(例如-v
以查看版本)时,它是有效的,而且问题似乎是导出到输出!用程序进行CCD_ 3和CCD_
- ls: cannot access >: No such file or directory
- ls: cannot access a.log: No such file or directory
重定向不是通过这种方式获得的。>
(或类似的)是在shell中进行重定向的语法。shell在exec
处理命令之前解释命令行并进行重定向,方法如下:
pid = fork();
switch(pid) {
case 0:
d = open("myfile",O_WRONLY);
dup2(d,STDOUT_FILENO); // redirect *stdout* to open file d by duplicating it
close(d); // now unused d (d is a duplicate of *stdout*
exec**(...); // now mutate to a new code which inherits open file descriptors
exit(1);
break;
case -1: // error case of fork
break;
default:
wait(NULL); // or whatever you want, don't wait for *background style*
break;
}
假设args
是传递给main()
函数的argv
1:
您的程序调用未定义的行为
while (args[i] != NULL)
{
printf("%sn", args[i]);
i++;
}
在该循环结束时,i
的值超出了args
数组的界限。因此
args[i] = ">";
args[i + 1] = "a.log";
尝试在禁止的位置写入,调用未定义的行为。
1不清楚,因为显然有一些代码丢失了