The full program is like this: / ************************************************** ************ / # include #include #include #include #include #include #include #include #include #define file_mode (s_irusr | s_iwusr | s_irgrp | s_iroth) / * Access License for new files Right * / int daemon_init (const char * pname) / * daemon process initialization function * / {INT i; pid_t pid; if ((pid = fork ())! = 0) EXIT (0); setsid (); / * The process becomes the first process of sessions, no longer control terminal * / signal (SIGHUP, SIG_IGN); / * Ignore the SIGHUP signal and again fork * / if ((pid = fork ())! = 0) EXIT (0); chDIR ("/"); / * Change the work directory * / umask (0); / * Clear file creation shield * / for (i = 0; i <64; i ) / * Close all open file descriptors * / Close (i); OpenLog (PNAME, LOG_PID, 0);} void write_file (void) {INT FDD; FDD = Open ("cc.log", o_wronly | o_append); Write (FDD, "Hello", 5); / * Write in the file * / close (fdd);} int main (int Argc, char ** argv) {Int fd; fd = creat ("cc.log", file_mode); / * Create a file * / daemon_init Argv [0]); / * daemon process initialization function * / write_file (); close (fd); exit (0);
/ ************************************************** *** / The result is the ability to produce "cc.log" files, but there is no data in front. In the Internet, many friends give comments. Some people say: "FD = Open (" cc.log ", o_creat | o_rdwr, file_mode) creates files, then Write is ok."; Some people said: "The file created by Create has not released, to first close (FD) ), The following Open actually should not succeed "; some people say that it may be a problem with File_Mode. Finally, I found that "ChDIR (" / ") in daem (" / "); / * changes the working directory * /" makes the following Open function can't find the file. Just after the correction.