linux下使用c++建立守護程序
阿新 • • 發佈:2019-01-07
#include<stdio.h>
#include<stdlib.h>
#include<string>
#include<iostream>
#include<fcntl.h>
#include<unistd.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<sys/stat.h>
using namespace std;
#define MAXFILE 65535
//實現一個守護程序:每隔5秒在/tmp/dameon.log中寫入一句話
int main(){
pid_t pc;
int i,fd,len;
//char *buf="this is a Dameon\n";
string buf="this is a Dameon\n";
//len = strlen(buf);
len=buf.size();
pc = fork(); /*第一步:建立子程序*/
if(pc<0){
printf("error fork\n");
exit(1);
}else if(pc>0){//父程序退出
exit(0);
}
setsid(); /*第二步:在子程序中建立新會話*/
char szPath[1024];
if(getcwd(szPath, sizeof(szPath)) == NULL)
{//獲得當前路徑
perror("getcwd");
exit(1);
}
//printf("current working directory : %s\n", szPath);
//chdir("/"); /*第三步:改變當前目錄為根目錄*/
chdir(szPath);
umask(0); /*第四步:重設檔案許可權掩碼*/
for(i=0;i<MAXFILE;i++) /*第五步:關閉檔案描述符*/
close(i);
while(1){
//if((fd=open("/tmp/dameon.txt",O_CREAT|O_WRONLY|O_APPEND,0600))<0){
if((fd=open("dameon.txt",O_CREAT|O_WRONLY|O_APPEND,0600))<0){
perror("open");
exit(1);
}
//write(fd,buf,len+1);
write(fd,buf.c_str(),len);//寫入檔案
close(fd);
sleep(5);
}
return 0;
}
相關命令:
ps aux | grep 檔名
kill -9 程序ID