Description of the problem
I am working on a large project that uses a logger for debugging. Since I like to track what happens in some CUDA kernels, I tried to find a way to redirect printfmy CUDA kernels to stringstream(or any thread), which can then be sent to the registrar.
Possible Solution
I managed to do this using the following code:
#include <cuda.h>
#include <stdio.h>
#include <unistd.h> // dup
#include <iostream>
#include <sstream> // stringstream
#include <fstream> // ofstream
char* output_file = "printf_redirect.log";
__global__ void printf_redirect(int* src, int* res)
{
res[threadIdx.x] = threadIdx.x;
printf(" %i: Hello World!\n", res[threadIdx.x]);
}
int main()
{
using namespace std;
const uint N = 2;
int *d_A, *d_B, *h_A, *h_B;
size_t size = N * sizeof (int);
cudaMalloc (&d_A, size);
cudaMalloc (&d_B, size);
h_A = (int*) malloc (size);
h_B = (int*) malloc (size);
cudaMemcpy (d_A, h_A, size, cudaMemcpyHostToDevice);
std::cout << "std::cout - start" << std::endl;
printf ("stdout - start\n");
std::cout << "Output to stdout:" << std::endl;
printf_redirect<<<1,1>>> (d_A, d_B);
cudaDeviceSynchronize ();
std::stringstream ss;
std::streambuf* backup_cout = std::cout.rdbuf ();
std::cout.rdbuf (ss.rdbuf ());
char buf[1024] = "";
int backup_stdout = dup (fileno (stdout));
freopen ("/dev/null", "w", stdout);
setbuf (stdout, buf);
std::cout << "Redirected output:" << std::endl;
printf_redirect<<<1,N>>> (d_A, d_B);
cudaDeviceSynchronize ();
ss << buf;
std::ofstream outFile;
outFile.open (output_file);
outFile << ss.str ();
outFile.close ();
fflush (stdout);
setbuf (stdout, NULL);
fclose (stdout);
FILE *fp = fdopen (backup_stdout, "w");
fclose (stdout);
*stdout = *fp;
std::cout.rdbuf (backup_cout);
std::cout << "std::cout - end" << std::endl;
printf ("stdout - end\n");
cudaMemcpy(h_B, d_B, size, cudaMemcpyDeviceToHost);
cudaFree(d_A);
cudaFree(d_B);
free (h_A);
free (h_B);
}
For this, I used the following questions:
Running the program, we get the console:
std::cout - start
stdout - start
Output to stdout:
0: Hello World!
std::cout - end
stdout - end
And in printf_redirect.log:
Redirected output:
0: Hello World!
1: Hello World!
Question
? (, CUDA C/++)
, , .