我的代码粘贴在下面。
我正在尝试使用dup2将输出重定向到文件。
如果我使用它来重定向,它工作得很好(如果我删除了注释),输出在文件中,而不是在标准输出上。例如: ls > test,结果是ls输出到test。
问题是ls,没有>不会输出任何东西。如果我保留注释ls的输出,尽管没有重定向的能力。
redirect为<或>或nothing redirect1是要重定向到的文件的路径
命令是带有命令命令的pices的cstring数组
带有注释代码的示例输出
xxxxx@myshell:/home/majors/kingacev/ubuntumap/cop4610/proj1> ls
a.out myshell.c myshell.c~
xxxxx@myshell:/home/majors/kingacev/ubuntumap/cop4610/proj1>使用未注释的代码
xxxxx@myshell:/home/majors/kingacev/ubuntumap/cop4610/proj1> ls
xxxxx@myshell:/home/majors/kingacev/ubuntumap/cop4610/proj1>
/*
if (!strcmp(redirect[0],">")){
if ((fd = open(redirect[1], O_RDWR | O_CREAT)) != -1)
dup2(fd, STDOUT_FILENO);
close(fd);
}
*/
if (command[0][0] == '/'){
int c = execv(command[0], commands);
if (c != 0){
printf("ERROR: command does not exist at path specified\n");
exit(0);
}
}
else if (!execv(path, commands)){
exit(0);
}发布于 2014-01-30 22:28:48
这段代码可以工作,重定向到file.out
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
int main(void)
{
int fd;
char *redirect[] = { ">", "file.out" };
char *command[] = { "/bin/ls", "-l", 0 };
if (!strcmp(redirect[0], ">"))
{
if ((fd = open(redirect[1], O_WRONLY | O_CREAT, 0644)) != -1)
{
fprintf(stderr, "Dupping stdout to %s\n", redirect[1]);
dup2(fd, STDOUT_FILENO);
close(fd);
}
}
if (command[0][0] == '/')
{
execv(command[0], command);
fprintf(stderr, "ERROR: command %s does not exist at path specified\n", command[0]);
return(1);
}
else
{
fprintf(stderr, "ERROR: not handling relative names like %s\n", command[0]);
return(1);
}
return 0;
}此代码也可以工作,而不是重定向到文件:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
int main(void)
{
int fd;
char *redirect[] = { "<", "file.in" };
char *command[] = { "/bin/ls", "-l", 0 };
if (!strcmp(redirect[0], ">"))
{
if ((fd = open(redirect[1], O_WRONLY | O_CREAT, 0644)) != -1)
{
fprintf(stderr, "Dupping stdout to %s\n", redirect[1]);
dup2(fd, STDOUT_FILENO);
close(fd);
}
}
if (command[0][0] == '/')
{
execv(command[0], command);
fprintf(stderr, "ERROR: command %s does not exist at path specified\n", command[0]);
return(1);
}
else
{
fprintf(stderr, "ERROR: not handling relative names like %s\n", command[0]);
return(1);
}
return 0;
}请注意,它设置了command阵列并使用execv(command[0], command); -这是推荐的业务处理方式。您的代码似乎有一个变量commands,可能包含程序的参数;您还可能有一个变量path,可能包含程序的路径名。因为我们看不到它们里面是什么,所以很难知道它们包含了什么,以及哪里可能存在问题。注意command数组末尾的显式空指针(0)。这一点至关重要。还要注意的是,错误消息指出了失败的原因。没有什么比一个程序说“它出错了”而没有确定“它”是什么更令人沮丧的了。
https://stackoverflow.com/questions/21458491
复制相似问题