1. 程式人生 > >由於memory 不足而導致fork失敗

由於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許可權