Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fork processes in R

Tags:

fork

r

I'm trying to understand the forking system implemented by R's multicore package. The package example is:

p <- fork()
if (inherits(p, "masterProcess")) {
  cat("I’m a child! ", Sys.getpid(), "\n")
  exit(,"I was a child")
}
cat("I’m the master\n")
unserialize(readChildren(1.5))

but it doesn't seem to work when pasted in the R interactive console. Does anyone have an example of using fork() with R's multicore or parallel packages?

like image 750
Ben Ogorek Avatar asked Apr 13 '14 16:04

Ben Ogorek


People also ask

What does forking a process do?

When a process calls fork, it is deemed the parent process and the newly created process is its child. After the fork, both processes not only run the same program, but they resume execution as though both had called the system call.

How many child process will be created with 4 fork () calls?

Fork #4 is executed by half of the processes created by fork #3 (so, four of them). This creates four additional processes. You now have twelve processes.

Do forked processes run parallel?

Once forked, the processes both run independently and concurrently. It depends. If you have multiple cores, then they run in parallel.

Where does a forked process start?

The fork starts from line 3, the point where the fork occurred. Show activity on this post. When fork returns, it returns in both the parent (returning the PID of the child) and the child (returning 0). Execution continues from there in both the parent and the child.


1 Answers

The fork example in the multicore package 'works for me' ; try example(fork). fork is only supported on non-Windows systems.

I think the equivalent functions in parallel are mcparallel() to fork and then evaluate an expression, and mcollect() to retrieve the result when done. So

id = mcparallel({ Sys.sleep(5); TRUE })

returns immediately but the process is running, and

mccollect(id)

will return TRUE after 5 seconds. There is no communication other than the collection between the forked and master process; it would be interesting and not too challenging to implement two-way communication using, e.g., sockets.

like image 189
Martin Morgan Avatar answered Nov 01 '22 11:11

Martin Morgan