由于memory 不足而导致fork失败

fork fail for(errno=12, out of memory).
fork因为内存不足而调用失败
because fork need twice memory to spawn a new thread which same with current one.
原因是因为fork时需要的内存和当前的process所使用的内存要一样大,如果当前process使用了很大的内存的话,在fork时,可能会超出系统的内存大小,从而导致fork失败。


how to solve it, there have two method
1. posix_spawn
代码例:
 #include <spawn.h>
 #include <sys/wait.h>
 #include <stdlib.h>
 extern char **environ;
 
 void run_cmd(char *cmd)
 {
     pid_t pid; 
     char *const argv[] = {"sh", "-c", cmd, NULL};
     int status;
     printf("Run command: %s\n", cmd);
     status = posix_spawn(&pid, "/bin/sh", NULL, NULL, argv, environ);
     if (status == 0) { 
         printf("Child pid: %i\n", pid);
         if (waitpid(pid, &status, 0) != -1) {
             printf("Child exited with status %i\n", status);
         } else {
             perror("waitpid");
         }    
     } else {
         printf("posix_spawn: %s\n", strerror(status));
     }    
 }
 
 
     std::stringstream cmd;
     cmd << "ps ax -o pid,rss | grep " << getpid() << " | awk '{print \"rss : \" $2}' >> /tmp/summary.txt";
     std::cout << cmd.str().c_str() << std::endl;
     //get rss and echo to tmp file	 
	 char myCmd[1024];
     strcpy(myCmd, cmd.str().c_str());
     run_cmd(myCmd);



2. echo 1 > /proc/sys/vm/overcommit_memory //需要root权限

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值