[英]Program will not exit after calling exit()
我有以下代码。 有人可以向我解释为什么键入“退出”时程序不会退出。 该程序可以运行,如果您在它开始时键入 exit,它就可以运行。 输入 a 后程序不会退出,例如输入 a 然后 b 然后 c 您必须输入 exit 4 次才能退出程序
#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <signal.h>
#include <string.h>
#include <cstdlib>
#include <stdlib.h>
#include <stdio.h>
#include <wait.h>
using namespace std;
//*********************************************************
//
// Extern Declarations
//
//*********************************************************
using namespace std;
extern "C" {
extern char **gettoks();
}
//*********************************************************
//
// Main Function
//
//*********************************************************
int main(int argc, char *argv[])
{
// local variables
int ii;
char **toks;
int retval;
pid_t pid;
int status;
char folder[80];
retval = 0;
cout << "Welcome to Island Shell" << endl;
while (true)
{
printf("Island Shell$ ");
toks = gettoks();
if (toks[0] != NULL)
{
if( !strcmp( toks[0], "exit" ))
{
exit(0);
}
pid = fork();
if (pid == 0)
{
strcpy(folder,"/bin/");
strcat(folder,toks[0]);
execv(folder,toks);
}
else
{
wait(&status);
}
}
}
return (retval);
}
您没有显示char **gettoks()
,因此很难确定,但这是我的猜测,假设 function 返回您的键盘输入。
当你输入 1 时,你会得到tok[0]==1
,然后fork()
创建同一进程的第二个副本,并在它结束时等待。 目的是通过调用execv
用另一个程序替换这个新进程,但execv
找不到名为1
的程序并且失败,因此您最终得到了同一进程的 2 个副本。
通过输入 2 和 3 重复此操作后,您最终会得到 4 个进程副本,彼此等待。 退出所有 4 个进程需要 4 个exit
命令。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.