如何在C/ c++中创建一个微shell

How to create a microshell in C/C++?

本文关键字:一个 shell 创建 c++      更新时间:2023-10-16

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