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会将其视为代码(并去掉这些空格)。要缩进,只需提供额外的空间。 –