1
我想實現我自己的shell,有很多東西不能工作,但現在我試圖解決第一個錯誤。 當我的shell正在運行,並且我作爲第一個命令輸入exit時,它可以正常工作,但是,當我輸入exit作爲第二個輸入時,我應該寫入exit以退出shell,如果我輸入它作爲第三個命令,我必須再輸入2次,依此類推。 這是我的代碼。在C中退出(0)只能偶爾工作
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
int argumentsnum;
int status;
char *arguments[30];
char *temp;
int processes_count=0;
printf("My Shell\n");
while (1)
{
char input[60];
printf("Enter command\n");
while (fgets(input, sizeof(input), stdin) == NULL)
{
printf("Enter command \n");
} /*end whileloop*/
for (argumentsnum = 0; argumentsnum < 31; argumentsnum++)
{
temp = strtok(input, " \t\n");
if (temp != NULL)
{
arguments[argumentsnum] = temp;
} /*endif*/
} /*end forloop*/
if (strcmp(arguments[0], "exit") == 0)
{
printf("Exiting shell\n");
int i;
For(i=0;i<processes_count;i++){
exit(0);
}
} /*endif*/
pid_t id = fork();
processes_count++;
if (id == -1)
{
perror("Grab your own fork :@ \n");
exit(1);
} /*endif*/
else if (id == 0)
{
execvp(arguments[0], arguments);
} /*endelse*/
else
{
wait(&status);
}
} /*end while(1)*/
} /*endmain*/
請縮進您的代碼 –
您的'execvp'調用有一個大問題,因爲您沒有正確終止該數組。最後一項必須是「NULL」指針。 –
輸入是字符60,所以你的fgets應該少一個來容納結尾的零 –