我正在用 C 创建一个简单的 Unix shell。我使用 fork() 克隆进程并使用 exec 执行新进程。当您第一次在 shell 中输入数据时,它工作正常。但是当它出现时,第二次迭代 fork 返回 -1。
例如
...>ls -l/
/结果在这里/
...>ls -l/
fork 失败
部分代码:
int execute(char path[80],char *args[]){
pid_t pid;
if((pid=fork())<0){
printf("forking failed"); // The forking failed due to Cannot allocate memory error
exit(0);
}else if(pid==0){
execv(path,args);
}else{
wait(NULL);
}
return 0
}
路径是“bin/ls”,参数是“ls”,NULL
主要是看起来像
int main(){
while(1){
//read from keyboard
//find the program path
//fill args
execute(path,args);
}
}
最佳答案
将您的第一个 if
分支更改为:
if((pid=fork())<0){
perror("forking failed");
exit(0);
}
这会告诉你哪里出了问题。
关于c - 我在 forking() 上收到 "Cannot Allocate Memory"错误的可能原因是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8031774/