Summary: Use Fputs () to write data to a file, to see the results in real time, you need to use Fflush to clear the buffer
/** Title: Write a daemon that writes the current time to the file Time.log every 3 seconds, * requires that the Init_daemon system call cannot be used. * */#include<stdio.h>#include<stdlib.h>#include<string.h>#include<time.h>#include<errno.h>#include<unistd.h>#include<sys/types.h>#include<sys/stat.h>voidGettime_now (Char*ptime) {time_t Tdata=0; //get current system timeTime (&tdata); //defining time structure body variables structTM *eventtime =NULL; //turn time_t type to struct TM pointer typeEventtime = localtime (&tdata); //Tm_year represents year, starting from 1900 intT_year = Eventtime->tm_year +1900; //month, month starting from 0 intT_mon = Eventtime->tm_mon +1; //Day intT_day = eventtime->Tm_mday; //hours intT_hour = eventtime->Tm_hour; //points intT_min = eventtime->tm_min; //seconds intT_sec = eventtime->tm_sec; sprintf (Ptime,"%d-%d-%d%d:%d:%d\n", T_year, T_mon, T_day, T_hour, T_min, t_sec);}intMainvoid) {pid_t pid=Fork (); if(PID = =-1) {perror ("fork () Err"); return-1; } if(PID = =0) { //create a new session periodSetsid (); //set the current directory as the root directoryChDir"/"); //Set directory PermissionsUmask0); Close (Stderr_fileno); Close (Stdin_fileno); FILE*PFA =NULL; PFA= fopen ("/home/test/1/time.log","a"); if(PFA = =NULL) {Perror ("fopen () Err"); return-1; } //every 3 seconds intseconds =0; while(1) {seconds=3; Do{seconds=sleep (seconds); } while(Seconds >0); //Get current Time Chartimearr[ -] = {0 }; Gettime_now (Timearr); strcat (Timearr,"\t\t print time \ n"); printf ("%s", Timearr); //Write Filefputs (Timearr, PFA); //Flush Buffersfflush (PFA); } } Else if(PID >0) {exit (0); } return-1;}
. suffixes:.c. OCC=Gccsrcs=hello.cobjs=$ (srcs:.c=. O) EXEC=serSRCS1= TEC01.COBJS1=$ (srcs1:.c=. O) EXEC1=cltstart:$ (OBJS) $ (OBJS1) -o $ (EXEC) $ (OBJS) -o $ (EXEC1) $ (OBJS1) "^_^-----OK------^_^". C.O: -wall-g-o [email protected]-C $< clean: -F $ ( Objs)F $ (EXEC)
Linux Linux program Exercise 17