From jeroenooms at gmail.com  Wed Jan 25 05:10:41 2017
From: jeroenooms at gmail.com (Jeroen Ooms)
Date: Tue, 24 Jan 2017 20:10:41 -0800
Subject: [Rd] parallel::mc*: Is it possible for a child process to know
 it is a fork?
In-Reply-To: <CAFDcVCRtpGfSvUxyQKSoufWLCAeXVCTMpn6x9WFL9F1SJh68AA@mail.gmail.com>
References: <CAFDcVCRtpGfSvUxyQKSoufWLCAeXVCTMpn6x9WFL9F1SJh68AA@mail.gmail.com>
Message-ID: <CABFfbXu-VkzaGJqmkNUDk7GvXgF0T6SazukGFza9PSmozBs5fA@mail.gmail.com>

On Tue, Jan 24, 2017 at 7:06 PM, Henrik Bengtsson
<henrik.bengtsson at gmail.com> wrote:
> When using multicore-forking of the parallel package, is it possible
> for a child process to know that it is a fork?

R internally uses R_isForkedChild to prevent certain operations within
the fork. However I don't think this is exported anywhere. You could
do something like:

  extern Rboolean R_isForkedChild;
  SEXP is_forked(){
    return ScalarLogical(R_isForkedChild);
  }

But that won't be allowed on CRAN:

* checking compiled code ... NOTE
  Found non-API call to R: ?R_isForkedChild?
  Compiled code should not call non-API entry points in R.

Another method would be to look at getppid(2) and getpgid(2) to lookup
the parent-id and group-id of the current process and test if it
matches that of the (parent) R process.

If you are only interested in limiting further parallelization within
the fork, perhaps you can simply use parallel::mcaffinity to restrict
the forked process to a single core.



[Rd] parallel::mc*: Is it possible for a child process to know it is a fork?
Jeroen Ooms