First, this log file is not very frequently written, and each row is a valid log. I want the PHP program to listen to this file, whenever it is written to a line, my PHP automatically read into a row, make analysis and then do the appropriate processing. How do you do it?
Reply content:
First, this log file is not very frequently written, and each row is a valid log. I want the PHP program to listen to this file, whenever it is written to a line, my PHP automatically read into a row, make analysis and then do the appropriate processing. How do you do it?
The basic principle is as Icode said. The simplest way to achieve this is to:
while (1) { Check file length or file modification time If there is a change, read sleep from the current point to a certain time}
The disadvantage is that if there is a problem with the program writing, PHP that executes for a long time is easy to crash.
Of course, you can not use the above loop sleep, instead of remembering the last way to read the location, and then put the check code in cron, so that every time PHP execution is recycled resources, not easy to crash, but there will be less than 1 minutes of delay. Can be combined with the previous approach, so that the program executes 1 minutes or so to quit to alleviate the delay problem, but note that the previous process has not exited after a process that has started the competition issue.
In addition, there are already inotify,php in Linux has the corresponding ext, can listen to the write event of the specified file. The advantage is the complete kernel implementation, the event callback mechanism, the CPU occupies very low, the disadvantage is to install the extension, in addition to familiar with the use of inotify.
The above method should be noted that it is possible to detect the change, the writer has not completed a complete line, need to do a buffer in the inspection program, when detected in the buffer in the presence of \ n can be considered to be the end of a line.
I hope the above is helpful to you.
Stat Gets the last modified time ...
Fseek Navigate to the last line ... fread read ...