C++ 如何在C/C++;?

C++ 如何在C/C++;?,c++,c,shell,unix,pid,C++,C,Shell,Unix,Pid,我的任务是“在C/C++中创建一个微shell”,我正试图弄清楚这到底意味着什么。到目前为止,我有这个C代码: #include <sys/types.h> #include <sys/wait.h> #include <stdio.h> #include <string.h> #include <iostream> #include <sstream> #include <stdlib.h> #include

我的任务是“在C/C++中创建一个微shell”,我正试图弄清楚这到底意味着什么。到目前为止,我有这个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

我需要向代码中添加什么才能做到这一点?另外,我将如何修改它以接受带有两个单词的命令,例如cat file.txt?谢谢您的帮助。

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

$ prgm4 # You want this...
$ /path/to/my/program/prgm4 # ...Instead of this.
如果是这样,它与程序本身没有任何关系。您需要将程序移动到变量中的某个位置,如Linux上的/usr/bin,或者编辑PATH变量以包含它已经在的目录。例如:

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

有关更多详细信息,请参阅超级用户问题。

在执行stuff之前,您应该关注接收输入。该命令是否需要正确处理空格?例如,是否需要正确读取带有空格.txt“”的
cat”文件?文件名中没有空格,尽管我最终将不得不使用pipe()在程序中使用“| |”作为管道。我更担心的是如何从命令行调用我的程序,尽管只使用它的名称。我认为这意味着把我的C++程序变成一个shell?一些样式点:不要使用固定长度的缓冲区。代码>返回0
而不是退出(0);使用C或C++,不同时使用;使用C++;使用
iostream
而不是
f*
;使用
std::getline
。是的,谢谢!“微地狱”这个词让我很困惑,现在我知道怎么做了。你知道我需要做什么来接受一个有空格的命令吗?比如“cat file.txt”?非常感谢。我想他可能在问如何让编译器使用他的名字,而不仅仅是生成“a.out”,但我可能错了。对于空格,您可以使用popen或system而不是exec*来运行命令,并在带有空格的参数周围加引号(如果它总是在posix系统上,那么可能是popen)
$ PATH="/path/to/my/program:$PATH"