【发布时间】:2016-07-04 17:26:16
【问题描述】:
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在后台执行进程?
【问题讨论】:
-
if(f[0]=="exit")。 C 中的字符串不能使用==运算符进行比较。需要使用strcmp。 -
请学会使用编辑框左上角的
{}格式工具来保持code/data/errorMsgs/etc的格式。祝你好运。 -
这篇文章不可读。请记住,如果一行以 4 个空格开头,堆栈溢出将其视为代码(并删除这些空格)。要缩进,只需提供额外的空格。
-
现在我可以执行退出命令,但我想在我的代码中实现在后台执行命令,如“ls&”.. 请问我该怎么办?
-
@A.Mohsen:你应该花几天(或几周)的时间阅读(书籍和源代码)。我们不会做你的功课。一个小外壳至少有一千行源代码,我们不会为您编写它们。你需要学习 & 实验