CUDA-1.6ΒΆ

A call to fork must be immediately followed to a call to exec

Required inputs: IR

CUDA 1.6 [fork] A call to fork must be immediately followed to a call to exec

In programs that duplicate themselves via the fork system call, a call to the exec system call must be made immediately following the call to fork. After the fork call and before the exec call, the following should be avoided:

  • Calling any CUDA library interface.
  • Using any objects residing in storage allocated by CUDA library interfaces.
  • Using any managed storage duration object (e.g. __managed__).
Scope: Host.
Audience: CUDA C++.
Category: Required.
Hardware Applicability: All Compute Capabilities.
Rationale

CUDA does not duplicate any of its internal data structures or threads to other processes upon a call to fork. Any use of CUDA after a call to fork and before a subsequent call to exec has undefined behavior.

Example 1 (Bad)
# include <cuda_runtime.h>
# include <cassert>
# include <unistd.h>
# include <sys/wait.h>
# include "testTerminate.h"
int
main() {
  float *v_d;
  int gpucount;
  testTerminate(cudaGetDeviceCount(&gpucount));
  if (fork() == 0) {
    // all uses of CUDA before a call to exec have undefined behavior.
    testTerminate(cudaSetDevice(0));
    cudaError_t const error0 = cudaMalloc(&v_d, 1000*sizeof(float));
    assert(cudaSuccess == error0);
  }
  wait(NULL);
  return 0;
}
Example 2 (Good)
# include <cuda_runtime.h>
# include <cassert>
# include <unistd.h>
# include <sys/wait.h>
int
main(int argc, char **argv)
{
  int gpucount;
  cudaError_t const result0 = cudaGetDeviceCount(&gpucount);
  assert(result0 == cudaSuccess);
  if (fork() == 0) {
    execl("/bin/ls", "ls", "-l", "/tmp/kris", (char *) 0);
    assert(0);
  }
  wait(NULL);
  return 0;
}
Excerpt from NVIDIA CUDA C++ Guidelines for robust and safety-critical programming, Version 3.0.1, Copyright (C) 2018-2023 NVIDIA Corporation.

Possible Messages

Key

Text

Severity

Disabled

cuda_fork_without_exec

A child of fork must not use cuda.

None

False

Options