C:使用system()命令

C:使用system()命令,c,error-handling,system,C,Error Handling,System,我正在写一个程序,它就像一个简单的shell。用户从命令行调用程序,并被提示输入发送到操作系统以完成的命令。它应该一直运行,直到用户输入“完成”,此时程序应该中断。我在输入done时遇到了一个问题-程序应该退出,但会打印 sh: -c: line 0: syntax error near unexpected token `done' sh: -c: line 0: `done' 在完成执行之前将其发送到终端。以下是我编写的适用代码: char isDone[] = "done\n"; //f

我正在写一个程序,它就像一个简单的shell。用户从命令行调用程序,并被提示输入发送到操作系统以完成的命令。它应该一直运行,直到用户输入“完成”,此时程序应该中断。我在输入done时遇到了一个问题-程序应该退出,但会打印

sh: -c: line 0: syntax error near unexpected token `done'
sh: -c: line 0: `done'
在完成执行之前将其发送到终端。以下是我编写的适用代码:

char isDone[] = "done\n"; //fgets stores the new line character from the command line

do {
    printf(">>"); //print the prompt each time through the loop
    fgets(command, 50, stdin); //get a line from the terminal
    system(command);
} while (strcmp(command, isDone) != 0); //break the loop if the user types in done
我认为这个错误与“done”不是有效的UNIX命令有关,但我不确定如何处理这个错误。我尝试使用以下修复程序解决此问题:

if(system(command) == -1){
    printf("The OS doesn't recognize this command");
}
else
    system(command);
但这并没有解决问题,也没有将错误打印到屏幕上,并且产生了第二个问题,即两次打印命令/错误-一次在if条件块中,一次在else块中。我怎样才能解决这个问题

编辑
这是一个家庭作业问题,需要使用do。是否有使用do while的解决方案?

do…while构造在检查循环条件之前执行其主体。因此,当循环“意识到”用户输入了
done
,它已经尝试在循环体中作为命令执行该输入

解决此问题的最清晰方法是使用
break

while (1)
{
    fgets(command, 50, stdin);
    if (!strcmp(command, isDone)) break;
    system(command);
}

采用这种结构的原因是,每次迭代都包括在条件之前应该执行的操作(读取用户输入)和在条件之后应该执行的操作(使用
system()
执行命令)。因此,无论是
do…while
还是简单的
while
都不能让您直观地构造代码。<代码>破解< /Cord>关键字为您提供了一个将循环终止条件放在循环体中间的方法。

< P>执行顺序为:

fgets(command, 50, stdin); //get a line from the terminal
system(command);
strcmp(command, isDone) != 0
所以,行“done”被读取,发送到系统(它试图以shell命令的形式执行它,打印错误),然后才进行检查

您可以尝试类似的方法:

for(;;){
    printf(">>"); //print the prompt each time through the loop
    fgets(command, 50, stdin); //get a line from the terminal
    if(!strcmp(command, isDone)) break; //break the loop
    system(command);
}
编辑:如果要保留do,请执行以下操作:

printf(">>"); //print the prompt each time through the loop
fgets(command, 50, stdin); //get a line from the terminal
do {
    system(command);
    printf(">>"); //print the prompt each time through the loop
    fgets(command, 50, stdin); //get a line from the terminal
} while (strcmp(command, isDone) != 0); //break the loop if the user types in done
但是
break
版本显然更具可读性。

在fgets()之后,在if语句中执行system()调用:

if ( strcmp( isDone, command) != 0 ) {
    system( command );
}

因为这是一个家庭作业,我们需要使用一个do-while。你能想出一个使用do-while的解决方案吗?@itscharlieb如果你稍微考虑一下,我认为你可以想出一种方法,将这个概念应用到你自己的代码中,只基于你粘贴和pod回答的内容。这个中断是有效的,但它意味着do-while的比较没有任何用处,这就是为什么我不愿意用它来解决问题。因为这是一个家庭作业,我们需要用一段时间来做。您能想出一个使用do while的解决方案吗?-这是可能的,但不干净或没有代码重复。由于我所说的在终止条件之前和之后都有操作,
do…而对于这个目的,
是一个非常糟糕的控制流构造。我会告诉我的教授(我从来都不是一个很好或者很受欢迎的学生)。哈哈,好吧,我会让他知道的。