【发布时间】:2014-12-15 04:55:31
【问题描述】:
我正在尝试在 C 中实现一个基本的 shell,但是每当我的 shell 使用 execvp() 执行命令时,它就会跳出我希望它留在其中的循环。我怀疑这是因为我不太熟悉execvp。
相关代码:
int main()
{
int nCmd = 1; // Command number
char *line; // Initial command line
token *list; // Linked list of tokens
CMD *cmd; // Parsed command
int process (CMD *);
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);
// Lex line into tokens
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
}
return EXIT_SUCCESS;
}
以下是“流程”的相关部分:
int process (CMD *cmdList)
{
if ((cmdList->nLocal)>0)
{
for (int i = 0; i<cmdList->nLocal; i++)
{
setenv(cmdList->locVar[i], cmdList->locVal[i], 0);
}
}
if (cmdList->type==SIMPLE)
{
execvp(cmdList->argv[0],cmdList->argv);
}
return 0;
}
发生的事情是我通过了 main 循环中的第一个过程。但是,不是像我想要的那样读取命令行,而是在执行命令后,程序就结束了。如何让它留在 for 循环中?
【问题讨论】:
-
execvp()用新程序替换当前程序。为了在原来的 shell 程序中继续处理,你需要在子进程中先fork()然后execvp()。 -
请在此处RTFM:man7.org/linux/man-pages/man3/exec.3.html(第一句说明了一切:“exec() 系列函数将当前进程映像替换为新进程图片。")