我使用「int flag = [0或1]」來確定我的循環是否應該返回到do {}。 繼承人我的代碼我做錯了什麼,以結束此循環
void shell()
{
int flag = 1;
do
{
// Retrieve PID of the parent process.
pid_t shell_pid = getpid();
// Print shell prompt.
printf("{%i}$ ", shell_pid);
// Retrieve input from stdin.
char* input = NULL;
size_t input_size = 0;
getline(&input, &input_size, stdin);
char delim = ' ';
char **argvp;
int argc = makeargv(input, &delim, &argvp);
// Remove \n from last arg
char* lastarg = argvp[argc - 1];
while(*lastarg && *lastarg != '\n')
lastarg++;
*lastarg = '\0';
// Create a child process to handle user input.
pid_t pid = fork();
// Parent process.
if (pid != 0)
{
wait(NULL);
}
else // Child process
{
int i;
// Handle user input here!
//got some debugging tools here
printf("========DEBUG==========\n");
printf("There are %i args\n", argc);
for(i = 0; i < argc; i++)
{
printf("arg %i: \"%s\"\n", i, *(argvp + i));
}
printf("=====END DEBUG==========\n\n");
printf("********OUTPUT*********\n");
//handle "echo" here
if((i = strcmp(argvp[0],"echo")) == 0)
{
echo(argc, argvp);
}
//handle "exit" or "quit" here
if((i = strcmp(argvp[0],"exit")) == 0 || (i = strcmp(argvp[0],"quit")) == 0)
{
printf("got in the exit\n");
flag = 0;
}
}
printf("****END OUTPUT*********\n");
// Free memory allocated by getline().
free(input);
}while(flag == 1);
}
和我的輸入/輸出如下:輸入前綴$]
$ ./shelltest
{13158}$ try first string
========DEBUG==========
There are 3 args
arg 0: "try"
arg 1: "first"
arg 2: "string"
=====END DEBUG==========
********OUTPUT*********
****END OUTPUT*********
{13159}$ echo try another
========DEBUG==========
There are 3 args
arg 0: "echo"
arg 1: "try"
arg 2: "another"
=====END DEBUG==========
********OUTPUT*********
try another
****END OUTPUT*********
{13160}$ quit
========DEBUG==========
There are 1 args
arg 0: "quit"
=====END DEBUG==========
********OUTPUT*********
got in the exit
****END OUTPUT*********
****END OUTPUT*********
{13160}$
由於「在出口處得到了」輸出結果顯示,則標誌是立即設置爲0. 循環如何繼續?
是什麼讓你說循環繼續? – user2357112
,因爲我被重新提示輸入「{13160} $」 –