【问题标题】:How to create a microshell in C/C++?如何在 C/C++ 中创建一个 microshell?
【发布时间】: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

标签: c++ c shell unix pid


【解决方案1】:

如果我理解正确,您只是在询问如何使用程序名称运行程序,而不是使用文件的完整路径。

$ prgm4 # You want this...
$ /path/to/my/program/prgm4 # ...Instead of this.

如果是这样,它与程序本身没有任何关系。您需要将程序移动到 $PATH 变量中的位置,例如 Linux 上的 /usr/bin,或者编辑 PATH 变量以包含它已经在其中的目录。例如:

$ PATH="/path/to/my/program:$PATH"

更多详情请参阅this超级用户问题。

【讨论】:

  • 好的,谢谢! “microshell”这个词只是让我感到困惑,现在我知道如何做到这一点了。你知道我需要做什么才能接受带有空格的命令吗?像“cat file.txt”?谢谢!!
  • 我想他可能会问如何让编译器使用他的名字,而不仅仅是产生“a.out”,但我可能错了。
  • 对于空格,您可以使用 popen 或 system 而不是 exec* 来运行带有空格参数的引号的命令(如果它总是在 posix 系统上,那么可能是 popen)跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-22
  • 2016-01-14
  • 2018-07-16
  • 2010-10-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多