我有一个任务是“在 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?感谢您的帮助。
最佳答案
如果我没理解错的话,您只是在询问如何使用程序名称而不是文件的完整路径来运行您的程序。
$ prgm4 # You want this...
$ /path/to/my/program/prgm4 # ...Instead of this.
如果是这样,那与程序本身没有任何关系。您需要将程序移动到 $PATH
中的某个位置变量,如 Linux 上的/usr/bin,或编辑 PATH 变量以包含它已经在的目录。例如:
$ PATH="/path/to/my/program:$PATH"
参见 this super 用户问题以获取更多详细信息。
关于c++ - 如何在 C/C++ 中创建微 shell ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15505691/