title: CUDA initialization error after fork
body: <p>I get "initialization error" after calling fork().  If I run the same program without the fork, all works fine.</p>
  
  <pre><code>if (fork() == 0) {
      ...
      cudaMalloc(....);
      ...
  }
  </code></pre>
  
  <p>What would cause this?</p>
  
  <p>A complete example is below.  If I comment out the cudaGetDeviceCount call, it works fine.</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;unistd.h&gt;
  #include &lt;stdlib.h&gt;
  #include &lt;sys/types.h&gt;
  #include &lt;sys/wait.h&gt;
  #include &lt;cuda_runtime.h&gt;
  
  #define PERR(call) \
    if (call) {\
     fprintf(stderr, "%s:%d Error [%s] on "#call"\n", __FILE__, __LINE__,\
        cudaGetErrorString(cudaGetLastError()));\
     exit(1);\
    }
  
  int
  main(int argc, char **argv)
  {
    float *v_d;
    int gpucount;
  
    cudaGetDeviceCount(&amp;gpucount);
  
    if (fork() == 0) {
      cudaSetDevice(0);
      PERR(cudaMalloc(&amp;v_d, 1000*sizeof(float)));
    }
    wait(NULL);
    return 0;
  }
  </code></pre>
  
  <p>Simple Makefile:</p>
  
  <pre><code>PROGS = fork
  CUDA_PATH = /usr/local/cuda
  CXXFLAGS = -g -O0 -Wall
  CXXINCLUDES = -I$(CUDA_PATH)/include
  NVCC := $(CUDA_PATH)/bin/nvcc -ccbin $(CXX) -Xcompiler "$(CXXFLAGS)"
  
  fork: fork.cxx
          $(NVCC) $^ -o $@ $(LIBS)
  
  clean:
          (rm $(PROGS) *.o)
  </code></pre>
  
  <p>In this case, I am only trying to get the number of devices available from within the parent process.  This work-around does it:</p>
  
  <pre><code>  if (fork() == 0) {
      PERR(cudaGetDeviceCount(&amp;gpucount));
      return(gpucount);
    }
    wait(&amp;gpucount);
    gpucount =  WEXITSTATUS(gpucount);
  </code></pre>