【发布时间】:2015-06-04 05:32:20
【问题描述】:
我想在 argv 数组中给出的特定文件中重定向标准输出和标准输入。
例如,当我输入类似 - ./shell ls > test 的命令时
它应该被重定向到“测试”文件,现在我有点困惑,因为没有编写任何代码它会自动重定向到该文件,我想手动执行它,其次,当我输入一个命令时 - ./shell ls ”或“”和文件名时,输出打印(该文件中 ">" "
基本上,我正在使用 execvp() 和 fork() 创建一个 shell 命令。
这是我的代码,我可以在静态文件中重定向标准输出。
void call_system(char *argv[],int argc)
{
int pid;
int status=0;
signal(SIGCHLD, SIG_IGN);
int background;
/*two process are created*/
pid=fork();
background = 0;
if(pid<0)
{
fprintf(stderr,"unsuccessful fork /n");
exit(EXIT_SUCCESS);
}
else if(pid==0)
{
//system(argv[1]);
/*argument will be executed*/
freopen("CON","w",stdout);
char *bname;
char *path2 = strdup(*argv);
bname = basename(path2);
execvp(bname, argv);
fclose (stdout);
}
else if(pid>0)
{
/*it will wait untill the child process doesn't finish*/
//waitpid(pid,&status,0);
wait(&status);
//int tempid;
//tempid=waitpid(pid,&status,WNOHANG);
//while(tempid!= pid);// no blocking wait
if(!WIFEXITED(status) || WEXITSTATUS(status))
printf("error");
exit(EXIT_SUCCESS);
}
}
【问题讨论】:
-
只用
>和<以外的东西,比如./myprog -i input.file -o output.file。
标签: c linux shell execvp freopen