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权限