c - 我在 forking() 上收到 "Cannot Allocate Memory"错误的可能原因是什么?

标签 c shell unix fork

我正在用 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/

相关文章:

c - 如何在c/汇编程序中通过cpuid指令识别cpu品牌名称

c++ - 在 OpenMP 中访问线程的私有(private)内存

c - 这里的返回是如何进行的?

c - mmap 在 Intel (i7) 和 Arm 上的不同行为?

linux - 检查脚本命令中的错误

linux - 在 UNIX 文件系统中查找数值的最佳方法

perl fork 远程运行时无法正常工作(通过 ssh)

unix - 如何在文件中搜索模式并在命令行上删除 Unix 中的行?

linux - 检查通过 Cron 运行的 shell 脚本中的上一步

linux - 下面的脚本做了什么