c++ - 如何在 C/C++ 中创建微 shell ?

标签 c++ c shell unix pid

我有一个任务是“在 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/

相关文章:

c - 选项卡控件上的闪烁 - WIN32

mysql - 在shell脚本中执行MySQL命令?

c++ - 使用另一个程序调用正在运行的 C++ 程序中的函数

c++ - ostream& 引用是如何自动创建的?

c++ - MFC-C代码合并问题

c++ - VSE(visual studio enterprise)2015 上的 C++ 中的 ShellExecute 不起作用

C:将数组传递给指针函数

Cuda 重用事件来确定多个部分的执行时间

linux - 如何将最后一列移动到第 n 列?

bash - bash 选项卡补全如何工作?