int main(void) {
char in[512];
pid_t id;
int status, y, x, i = 1;
char *f[512];
char *v;
while(1)
{
printf("shell>");
fgets(in,512, stdin);
int size = strlen(in);// calculate dim of in execpt null
in[size-1] = '\0'; //null at the end because ls\n not executable
v = strtok(in, " ");
f[0] = v;
while (v = strtok(NULL, " ")) {
f[i] = v;
i++;
}
f[i] = NULL;
y = strcmp(f[0],"exit");
if (y == 0)
break;
id = fork();
if (id==0) { //child
execvp(f[0],f);
perror("failure");
exit(1);
}
else //parent
{
x=strcmp(f[i-1],"&");
if (x != 0)
waitpid(id, &status, 0);
}
}
}
在這段代碼中我可以執行shell命令,但是我不能執行command &
部分。我怎樣才能讓execvp
在後臺執行一個進程?執行後臺進程的Shell項目
'if(f [0] ==「exit」)'。使用'=='運算符不能比較C中的字符串。需要使用'strcmp'。 – kaylum
請學習使用編輯框左上角的格式化工具來保持代碼/數據/ errorMsgs/etc的格式。祝你好運。 – shellter
這篇文章是不可讀的。請記住,如果一行以4個空格開頭,Stack Overflow會將其視爲代碼(並去掉這些空格)。要縮進,只需提供額外的空間。 –