#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/wait.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
static void sig_child(int signo)
{
pid_t pid;
int stat;
while((pid=waitpid(-1,&stat,WNOHANG))>0);
return;
}
int main()
{
signal(SIGCHLD,sig_child);
int npid = -1;
npid = fork();
if(npid == 0){ //child
clearfile();
}else{ //parent
while(1){
sleep(3);
if(getpgid(npid) < 0){
kill(npid,9);
npid = fork();
if(npid == 0){
clearfile();
}
}
}
}
}
void clearfile()
{
struct stat statbuf;
char szpath[] ="/home/jzb/source/myprint.log";
int nret;
int fd ;
while(1){
nret = stat(szpath,&statbuf);
if(statbuf.st_size >= 1024*1024*1024){
fd = open(szpath,O_CREAT|O_TRUNC);
close(fd);
}
sleep(1);
}
}
主程序通过while循环不断的检测进程所属是否有效(通常情况下,当进程终止时,所属的进程组号为-1,为此,判断进程是否在运行)。如果检测到子进程结束,则将重启开启子进程。