views:

53

answers:

1

I am using ruby 1.8.7 and rails 2.3.4 . I am developing a plugin so I don't have too much of leeway.

In my controller I need to invoke a rake task. The rake task will take longer to finish so I am following the approach mentioned in Railscast which is

system "rake #{task} &"

This solution works great and everything is fine. I know this solution will not work on windows and I'm fine with that.

I started my server at port 3000. The controller was invoked which fired the rake task in the background. However if I ctrl +c my script/server and if I try to restart the server then I get this error.

Address already in use - bind(2) (Errno::EADDRINUSE)

Then I changed my code to do this

fork do
 system "rake #{task} &"
end

Still the same issue.

Does anyone how do I get around this problem of port 3000 getting blocked. Also any explanation of why rake task is blocking port 3000 would help.

+2  A: 

From ruby-docs: Kernel.fork [{ block }] => fixnum or nil Process.fork [{ block }] => fixnum or nil

Creates a subprocess. If a block is specified, that block is run in the subprocess, and the subprocess terminates with a status of zero. Otherwise, the fork call returns twice, once in the parent, returning the process ID of the child, and once in the child, returning nil. The child process can exit using Kernel.exit! to avoid running any at_exit functions. The parent process should use Process.wait to collect the termination statuses of its children or use Process.detach to register disinterest in their status; otherwise, the operating system may accumulate zombie processes.

The thread calling fork is the only thread in the created child process. fork doesn‘t copy other threads.

Final solution based on comments below:

command = "rake #{task} #{args.join(' ')}" 
p1 = Process.fork { system(command) } 
Process.detach(p1)
LymanZerga
Not working.Revised code p1 = fork { system(command) } Process.detach(p1)still getting address already in use
Neeraj Singh
Just to make sure there are no loose ends, could you change fork to Process.fork?
LymanZerga
same issue with Process.fork too.
Neeraj Singh
LymanZerga
Yeap that solved the problem. You should edit your answer and put this code as the final answer so that others could see it clearly. command = "rake #{task} #{args.join(' ')}" p1 = Process.fork { system(command) } Process.detach(p1)
Neeraj Singh