我目前使用C语言编写了一个基本的Bash实现。但是,当我尝试将标准输出重定向两次时,我遇到了问题。以下是相关代码:
阅读每个命令:
for ( ; ; ) {
printf ("(%d)$ ", nCmd); // Prompt for command
fflush (stdout);
if ((line = getLine (stdin)) == NULL) // Read line
break; // Break on end of file
list = lex (line);
free (line);
if (list == NULL) {
continue;
} else if (getenv ("DUMP_LIST")) { // Dump token list only if
dumpList (list); // environment variable set
printf ("\n");
}
cmd = parse (list); // Parsed command?
freeList (list);
if (cmd == NULL) {
continue;
} else if (getenv ("DUMP_TREE")) { // Dump command tree only if
dumpTree (cmd, 0); // environment variable set
printf ("\n");
}
process (cmd); // Execute command
freeCMD (cmd); // Free associated storage
nCmd++; // Adjust prompt
}
shell的部分我们的代码搞砸了:
if (cmdList->type==SIMPLE)
{
pid_t fork_result;
fork_result = fork();
if (fork_result < 0) {
fprintf(stderr, "Fork failure");
exit(EXIT_FAILURE);
}
if (fork_result == 0) {
if (cmdList->fromType==RED_IN)
{
int fe = open(cmdList->fromFile, O_RDONLY, 0);
dup2(fe, 0);
close(fe);
}
if ((cmdList->toType==RED_OUT) || (cmdList->fromType==RED_APP))
{
int fd = open(cmdList->toFile, O_CREAT | O_WRONLY, 0666);
dup2(fd, 1);
close(fd);
}
execvp(cmdList->argv[0],cmdList->argv);
exit(EXIT_FAILURE);
}
else {
int status;
wait(&status);
}
}
当我只用一个简单的命令阅读时,最后一段代码完全符合我的意图。但是,当我使用for循环尝试重定向stout两次时出现问题。例如,我尝试运行:
cat Tests/star.wars > +Bash.tmp
cat +Bash.tmp
cat Tests/stk.txt > +Bash.tmp
cat +Bash.tmp
第一个命令写道,例如&#34; ABC&#34;到Bash.tmp。但是,当我运行第二个命令时,我希望它返回&#34; DE&#34;。但是,我得到了DEC&#34;作为输出。有什么问题?
答案 0 :(得分:0)
O_WRONLY
是“只写”权限。 O_TRUNC
是在打开时截断文件的内容。
- Etan Reisner