所以,我必须构建一个自定义 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/