我正在使用“int flag = [0 or 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}$
由于输出中显示了“got in exit”,因此 flag 立即设置为 0。循环如何继续?
你正在使用fork()
,父进程正在等待子进程退出,行:
printf("****END OUTPUT*********\n");
父进程和子进程都执行,所以你看到了两次。
我是一名优秀的程序员,十分优秀!