如何在C/ c++中创建一个微shell
How to create a microshell in C/C++?
我有一个任务是"在C/c++中创建一个微壳",我正试图弄清楚这到底是什么意思。到目前为止,我有这样的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"
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 删除一个线程上有数百万个字符串的大型哈希映射会影响另一个线程的性能
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 运行同一解决方案的另一个项目的项目
- 挂起和取消挂起一个文件DLL
- 用C++中的一个变量定义一个常量
- 函数向量_指针有不同的原型,我可以构建一个吗
- 如何将我的 cli 信息(变量等)共享到子进程,这是一个 bash shell 脚本
- 分叉:使用一个参数运行 shell 时资源暂时不可用
- 打开一个 Shell 程序,向其传递参数,然后返回结果
- 一个简短的c++文件和makefile:我可以在shell中制作,但在Eclipse中构建它时会遇到很多错误
- 开发一个交互式shell
- 在 Xcode 中创建一个新的"Shell Tool"目标以供使用 Google 测试
- 我该如何编写一个通过从shell运行来编译自己的c++程序
- 如何创建一个将命令行参数传递给shell脚本的c++程序
- Unix中的c++ Shell, execv:从函数动态创建并返回一个可用的第二个参数
- 使用ShellExecute发送一个shell脚本给sqlite3.exe
- 如何使用shell脚本运行一个进程两次
- 为什么我们需要写一个自己的复制程序,而我们可以使用复制shell命令
- 如何在C/ c++中创建一个微shell