Detaching Rails Processes
In my latest app, I’m emailing reports to people who click on a link. (Yes, I know this should be a button, but I just did it with a link because it was easy. If I have time, I’ll change it to a button.) Anyway, I’m attempting to use Process.fork to do this. What I have that works is:
def email_monthly_report monthyear = params[:monthyear] process = Process.fork do ReportMailer.send_monthly_report(current_user, monthyear).deliver # Process.kill("HUP", process) end Process.detach(process) redirect_to monthly_report_projects_path(:month => monthyear), :notice => "Report sent to #{current_user.fullname}<#{current_user.email}>" end
From everything that I’ve read, that Process.kill(“HUP”, process) line should be required. If I uncomment it, the email gets sent and the page is redirected correctly, but I get an error in the log.
projects_controller.rb:74:in `kill': no implicit conversion from nil to integer (TypeError)
My line process=Process.fork is always sets process to nil. So I apparently need to figure out how fork works. Time to fire up irb.
ruby-1.9.2-p0 > pid = fork do ruby-1.9.2-p0 > a = 100 ruby-1.9.2-p0 ?> end => 67773 ruby-1.9.2-p0 > pid.class => Fixnum ruby-1.9.2-p0 > pid => 67773 ruby-1.9.2-p0 > Process.kill("HUP",pid) => 1 ruby-1.9.2-p0 > exit
So what am I doing wrong? I really don’t want to kill the process, I just want to let it finish whenever it does. If I just take out the Process.kill line, everything does work as expected. Would there be a chance that the process could get stuck and I would need the kill line? I don’t know. But since I can’t get things to work properly with it, I’m just going to leave it out.