点击(此处)折叠或打开
-
#include <iostream>
-
#include <unistd.h>
-
#include <stdlib.h>
-
#include <signal.h>
-
#include <stdio.h>
-
#include <sys/types.h>
-
#include <sys/wait.h>
-
using namespace std;
-
class CChild{
-
private:
-
int value;
-
pid_t pid;
-
public:
-
CChild(int i){value=i;}
-
CChild(){value=0;}
-
int getValue(){
-
return value;
-
}
-
void setValue(int varValue){
-
value=varValue;
-
}
-
int getPid(){
-
return pid;
-
}
-
void setPid(int varPid){
-
pid=varPid;
-
}
-
int start(){
-
pid_t _pid;
-
_pid=fork();
-
printf("start child process:fork():%d\n",_pid);
-
if(_pid>0){
-
pid=_pid;
-
return 0;
-
}
-
else if(_pid <0){
-
pid=_pid;
-
return -1;
-
}else if(_pid == 0){
-
pid=getpid();
-
for(;;){
-
sleep(20);
-
printf("child process!value:%d,\tpid:%d\n",value,pid);
-
}
-
}
-
}
-
};
-
CChild cc[10]={0,1,2,3,4,5,6,7,8,9};
-
int log(char* str){
-
FILE *logfile;
-
logfile = fopen("/tmp/liveser.log","a+");
-
fputs(str,logfile);
-
fclose(logfile);
-
}
-
void child_quit(int sig){
-
int _pid,status;
-
char str[512];
-
_pid=wait(&status);
-
sprintf(str,"child exit!pid:%d",_pid);
-
log(str);
-
for(int i=0;i<9;i++)
-
{
-
if(_pid == cc[i].getPid())
-
{
-
cc[i].start();
-
}
-
}
-
}
-
int startMainServer(CChild *cc){
-
signal(SIGCHLD, child_quit);
-
int i,_cid;
-
for(i=0;i<9;i++){
-
printf("start child process:%d\n",i);
-
cc[i].start();
-
}
-
for(;;){
-
for(i=0;i<9;i++){
-
sleep(60);
-
printf("child %d is run!",cc[i].getPid());
-
}
-
}
-
}
-
int main()
-
{
-
//CChild cc[10]={0,1,2,3,4,5,6,7,8,9};
-
cout << "Hello world!" << endl;
-
int i=daemon(0,0);
-
if(i==0){startMainServer(cc);}
-
if(i != 0){
-
exit(0);
-
}
-
return 0;
- }