#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//Implement a daemon: Write a word in/tmp/dameon.log every 5 seconds 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 ();
/* First step: Create Subprocess */if (pc<0) {printf ("error fork\n");
Exit (1);
}else if (pc>0) {//Parent process exits exit (0); } setsid ();
/* Step two: Create a new session in the subprocess/char szpath[1024];
if (GETCWD (szpath, sizeof (szpath)) = = NULL) {//Get current path Perror ("GETCWD");
Exit (1);
}//printf ("Current working directory:%s\n", szpath); ChDir ("/");/* Step three: Change current directory to root directory/chdir (szpath); Umask (0);
/* Step Fourth: Reset the file permission mask/for (i=0;i<maxfile;i++)/* Fifth step: Close the file descriptor */
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);//writes file close (FD);
Sleep (5);
return 0; }
Related commands:
PS aux | grep filename
kill-9 process ID