c - 如何通过 popen 使用内置 shell 命令

标签 c shell gcc popen fgets

所以,我必须构建一个自定义 shell,它可以执行所有 sh 命令和位于/usr/bin 中的所有二进制文件以及 shell 中包含的其他二进制文件,但我目前无法使用 inbuild cd 并且不知道如何甚至可以通过 chdir 使其工作(我尝试了多次,但如果 chdir 在循环内,它会为每个 shell 重新创建一个 fork)。

如果你能帮助我,因为我是一名学生,并给我提示和建议,那就太好了。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "color.h"

int expertShell()
{       
    while(1)
    {
        FILE *fp;
        char path[1035], command[1024];
        printf(ANSI_COLOR_BLUE "☁  " ANSI_COLOR_RESET);
        fgets(command, sizeof(command)-1, stdin);

        if(strncmp(command, "cd", 2) == 0)
        {
            chdir(strtok(command, "cd "));
        }

        if(strncmp(command, "exit", 4) == 0)
        {
            exit(1);
        }

        if(strncmp(command, "ls", 2) == 0)
        {
            strcat(strtok(command,"\n"), " --color=always");
        }

        if(strncmp(command, "nano", 4) == 0 || strncmp(command, "vi", 2) == 0)
        {
            system(command);
        }
        else
        {
            fp = popen(command, "r");

            if (fp == NULL) {
                printf("Failed to run command\n" );
                exit(1);
            }

            while (fgets(path, sizeof(path)-1, fp) != NULL) {
                printf("%s", path);
            }

            pclose(fp);
        }
    }
}

最佳答案

if(cdInBuild != 0)

您需要实际调用该函数。正如所写,这是检查 cdInBuild 是否为非空函数指针(始终为真)。

if(cdInBuild(command) != 0)

关于c - 如何通过 popen 使用内置 shell 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34270842/

相关文章:

bash - sh 和 Bash 之间的区别

用于查找最坏可能路径的 c 程序的控制流程图

c - 将大型 const 结构传递给函数

c++ - GCC 的 -Wpsabi 选项到底有什么作用?压制它有什么影响?

c - c中的逐行输入

c++ - 错误,* 的运算符必须是指针

Bash:以编程方式获取命令的完成输出(例如,在变量中)

Linux如何等待远程pid(telnet)

c - 读取二进制文件并将所有数据存储到结构数组中

c - 了解 C 程序