【发布时间】:2013-03-19 16:54:20
【问题描述】:
我有一个任务是“在 C/C++ 中创建一个 microshell”,我正试图弄清楚这到底意味着什么。到目前为止,我有这个 C 代码:
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <sstream>
#include <stdlib.h>
#include <sys/utsname.h>
int main(void)
{
char buf[1024];
pid_t pid;
int status;
printf("%% ");
while (fgets(buf,1024,stdin) != NULL)
{
buf[strlen(buf) -1] =0; //remove the last character. Important!
if ((pid = fork()) <0)
printf("fork error");
else if (pid==0)
{ /* child */
execlp(buf, buf, (char *) 0);
printf("couldn't execute: %s", buf);
exit(127);
}//else if end
/* parent */
if ( (pid = waitpid(pid, &status, 0)) <0)
printf("waitpid error");
printf("%% ");
}//while end
exit(0);
}//main end
我需要能够仅使用它的名称来调用它。所以我的程序的名字是prgm4.cpp,所以我需要能够做到这一点:
%>prgm4
prgm4>(user enters command here)
我需要在我的代码中添加什么才能做到这一点?另外,我将如何更改它以接受带有两个单词的命令,例如 cat file.txt?感谢您的帮助。
【问题讨论】:
-
在执行内容之前,您应该专注于接收输入。
-
命令是否需要正确处理空格?比如是否需要正确读取
cat "file with spaces.txt"? -
文件名中没有空格,尽管我最终将不得不使用 pipe() 以某种方式使用“||”作为我程序中的管道。我更担心如何从命令行调用我的程序,尽管只使用它的名称。我认为这意味着将我的 C++ 程序变成一个 shell?
-
一些风格要点:永远不要使用固定长度的缓冲区;
return 0而不是exit(0);使用 C 或 C++,而不是两者;使用 C++;使用iostream而不是f*;使用std::getline。