[英]Creating a shell in C, execv() is unable to execute most commands
到目前為止,我知道在shell中可以使用的唯一命令是ls和echo。 當我嘗試觸摸或幫助之類的東西時,我什么也沒有,也沒有出現故障。
這是我執行命令的方法:
void mySystem(char * cmdargv[], char *searchpaths[], int numpaths, int numargs)
{
int pid=fork();
if(pid==0);
{
for(int i=0; i<numpaths; i++)
{
char * fullcmd = malloc(strlen(searchpaths[i] + strlen(cmdargv[0]) + 2));
sprintf(fullcmd, "%s/%s", searchpaths[i], cmdargv[0]);
//execv(fullcmd, cmdargv);
printf("%s",fullcmd);
free(fullcmd);
}
exit(0);
}
wait(NULL);
}
這是我的主要程序:
int main()
{
const char space[]="\n"; //"deliminator," specifies where to tokenize commands
int numpaths;
int numargs;
char *searchpaths[MAX_PATHS];
char *fullCMD[MAX_CMD];
InitializeArray(fullCMD, MAX_CMD);
InitializeArray(searchpaths, MAX_PATHS);
char cmd[MAX_CMD];
SaveSearchPaths(searchpaths, (int *) &numpaths); //fills the searchpaths array with
//the system PATH and returns the
//the size of the array, numpaths
while(1)
{
printf("> ");
fgets(cmd, MAX_CMD, stdin);
char *token;
token=strtok(cmd, space);
if(strncmp(cmd,"quit",4) == 0)
{
exit(0);
}
else if(strncmp(cmd, "path", 4)==0)
{
PrintAll(searchpaths, MAX_PATHS);
}
else
{
int i=0;
while(token!=NULL)
{
InsertStringAt(fullCMD,token,i);
token=strtok(NULL,space);
i++;
numargs+=1;
}
mySystem(fullCMD, searchpaths, numpaths, numargs);
}
InitializeArray()
函數將數組中的所有索引初始化為NULL
。 InsertStringAt()
將字符串插入數組中的某個索引中,並且SaveSearchPaths()
使用標記化的System PATH
填充searchpaths[]
數組。
當我在shell中輸入ls時,會發生以下情況:
./a.out
> ls
a.out arrayOfStrings.c arrayOfStrings.h arrayOfStrings.h.gch arrayOfStrings.o arrayOfStringsTester.c arrayOfStringsTester.o myshell.c mySystem.c out SaveSearchPaths.c
當我提供幫助時會發生以下情況:
$ ./a.out
> help
$
什么都沒發生。
當我觸摸時會發生以下情況:
> touch file
*** Error in `./a.out': free(): invalid next size (fast): 0x00000000006a2130 ***
*** Error in `./a.out': free(): invalid next size (fast): 0x00000000006a2130 ***
Aborted (core dumped)
任何想法為什么只有ls似乎起作用?
你這里有錯字
strlen(searchpaths[i] + strlen(cmdargv[0]) + 2)
/* ^ the ) goes here not ^ here
這是有效的,因為您要遞增searchpaths[i]
指針並在結果指針上執行strlen()
,這可能會導致未定義的行為,但這是有效的代碼,編譯器應正確地對其進行編譯。
正確的方法是
strlen(searchpaths[i]) + strlen(cmdargv[0]) + 2
另外,您應該檢查malloc()
沒有返回NULL
,這將指示錯誤。
如果存儲strlen()
的結果,則可以防止這種情況,並處理更多錯誤。 適應它也是很好的恕我直言,因為有時您可能需要多次使用該值,並且由於strlen()
計算該值,在這種情況下將其存儲起來更為有效,在這種情況下,唯一的好處就是清晰明了並改進處理錯誤和維護代碼的能力。
尚未測試,希望能奏效。
void mySystem(char * cmdargv[], char *searchpaths[], int numpaths, int numargs)
{
int pid=fork();
if(pid==0) /* remove junk semicolon */
{
for(int i=0; i<numpaths; i++)
{
char * fullcmd = malloc(strlen(searchpaths[i]) + strlen(cmdargv[0]) + 2); /* improve this expression */
sprintf(fullcmd, "%s/%s", searchpaths[i], cmdargv[0]);
//execv(fullcmd, cmdargv);
printf("%s",fullcmd);
free(fullcmd);
}
exit(0);
}
wait(NULL);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.