Requirement:
I need to run a background process (per a user request) that takes about 30 to 60 seconds to complete. I'd like to give the user some status feedback. Note: Toly is right, 'Background' is not required.
What's working:
The process prints about 20 status messages during this time and I retrieve them with a proc_open and listening on a read pipe using fgets. I can save those messages into a session var and using timestamps (to help debug) I can see that the session array is getting written to with these messages as the process progresses.
The Trouble:
My plan was to poll the server with ajax calls (every sec) to retrieve these session vars for display in the DOM. The bottleneck seems to be that the server cannot service the ajax request while it's still running the background process. Everything dumps out at once when the background process completes. From what I can tell, the issue is not with output buffering because using (debugging) timestamps saved with each process message shows the server is writing to the session var sequentially, so that's how I know the proc_open and pipe reads are working as I expect. The issue appears to be the server not being able to give the AJAX request it's JSON object until it is done with the process; or, probably more accurately, done with the loop that is reading the pipe.
Obvious Misconception:
I thought sending a process to the background (using &) might give me a solution here. Apparently I do not know the difference between a background process and a forked process. What benefit is gained - if any - by running a process in the background when doing so appears to make no difference to me in this scenario?
Possible Solutions:
- I do not expect the user initiated process that runs this process/scenario to be that heavy, but if there's something I can build into this solution that would help a heavy load then I would like to do that now.
- Is this a multi-threading (pthreads) or a multi-process (fork) solution?
- Or, should I save a process id, let go polling it with a while( .. fgets ..) statement and then come back to the process after the server has serviced the ajax request?
- I suppose I could run fake status messages and then response accurately when the results come back after completion. The time to process the request is not dependent upon the user, so my fake timing could be pretty accurate. However, I would like to know what the solution would be to provide real-time feedback.