我正在尝试编写一个简单的shell来支持所有常用功能。
到目前为止,尽管我采取了偶然的方法,但我已经获得了成功 - 我已经能够使用参数fork()新进程,但其他某些方法似乎无法运行。
当我运行我的shell时,像pwd,ls这样的函数可以帮助工作,而其他函数如cd,mkdir则没有 - 为什么这个&我可以做些什么研究/调查才能开始解决这个问题?
到目前为止,我已经包含了我的代码(虽然我不确定它是否真的有用)。
非常感谢
编辑:我的输出,当我的shell在cygwin中运行时,如果输入“cd / cygdrive / c”,则输出为“Command not found”
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
const int MAX_ARGS = 9;
size_t nBytes = 64; //Data type representing size of objects (unsigned)
int bytesRead = -1;
char *cmd = NULL;
char prompt[] = "DaSh-> ";
int argc;
char **argv;
int pid;
int childpid;
int status;
void process();
int readcmd();
int main() {
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
while (1) {
bytesRead = -1;
printf(prompt);
while (bytesRead == -1) {
bytesRead = readcmd();
}
process(cmd); //process the single line input into arguments
if (strcmp(argv[0], "exit") == 0) { //If user types exit
exit(0);
}
childpid = fork();
if (childpid == 0) { //This is run by the child
execvp(argv[0], argv);
printf("Command not recognised\n");
exit(1);
}
else if (childpid > 0 ) {
waitpid(-1, &status, 0);
}
}
return 0;
}
int nrows = 10;
int ncolumns = 2;
void process(char argStr[]) {
argv = malloc(MAX_ARGS * sizeof(char *)); //Array of pointers to the char first letter of each argument
char delims[] = " \n"; //Delimit about space
int i = 0;
argv[i] = strtok(argStr, delims);
while (argv[i] != NULL) {
argv[++i] = strtok( NULL, delims);
}
argc = i;
}
int readcmd() {
return getline(&cmd, &nBytes, stdin);
}