#include <stdlib.h>
#include <unistd.h>
#include <iostream>
using namespace std;
class fork_process {
public:
static inline fork_process &get() {
static fork_process obj;
return obj;
}
void fork_now(int process_num) {
if (process_num <= 1 || process_num > MAX_PROCESS_NUM) {
return;
}
int parent_id = 0;
pid_t pid = fork();
if (pid < 0) {
return;
}
if (pid > 0) {
parent_id = getpid();
}
else {
// fork a child to do something
}
for (int i = 2;i < process_num;++i) {
if (getpid() != parent_id) {
continue;
}
pid = fork();
if (pid < 0) {
exit(EXIT_FAILURE);
}
if (0 == pid) {
// fork a child to do something
}
}
}
private:
fork_process() = default;
~fork_process() = default;
private:
static const int MAX_PROCESS_NUM = 100;
};
int main(int argc, const char **argv) {
if (argc >= 2) {
fork_process::get().fork_now(atoi(argv[1]));
}
cout << "process begin to work now." << endl;
while (true) {
sleep(1000);
}
return 0;
}