MCPcopy Create free account
hub / github.com/davisking/dlib / subprocess_stream

Method subprocess_stream

dlib/matlab/subprocess_stream.cpp:421–483  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

419// ----------------------------------------------------------------------------------------
420
421 subprocess_stream::
422 subprocess_stream(const char* program_name) : stderr(NULL), iosub(NULL)
423 {
424 if (access(program_name, F_OK))
425 throw dlib::error("Error: '" + std::string(program_name) + "' file does not exist.");
426 if (access(program_name, X_OK))
427 throw dlib::error("Error: '" + std::string(program_name) + "' file is not executable.");
428
429 child_pid = fork();
430 if (child_pid == -1)
431 throw dlib::error("Failed to start child process");
432
433 if (child_pid == 0)
434 {
435 // In child process
436 dup2(stdout_pipe.child_fd(), STDOUT_FILENO);
437 dup2(stderr_pipe.child_fd(), STDERR_FILENO);
438 stdout_pipe.close();
439 stderr_pipe.close();
440
441 char* argv[] = {(char*)program_name, nullptr};
442 char* cudadevs = getenv("CUDA_VISIBLE_DEVICES");
443 if (cudadevs)
444 {
445 std::ostringstream sout;
446 sout << "DLIB_SUBPROCESS_DATA_FD="<<data_pipe.child_fd();
447 std::string extra = sout.str();
448
449 std::string extra2 = std::string("CUDA_VISIBLE_DEVICES=") + cudadevs;
450 char* envp[] = {(char*)extra.c_str(), (char*)extra2.c_str(), nullptr};
451 execve(argv[0], argv, envp);
452 }
453 else
454 {
455 std::ostringstream sout;
456 sout << "DLIB_SUBPROCESS_DATA_FD="<<data_pipe.child_fd();
457 std::string extra = sout.str();
458 char* envp[] = {(char*)extra.c_str(), nullptr};
459 execve(argv[0], argv, envp);
460 }
461
462
463 // If launching the child didn't work then bail immediately so the parent
464 // process has no chance to get tweaked out (*cough* MATLAB *cough*).
465 _Exit(1);
466 }
467 else
468 {
469 // In parent process
470 close(data_pipe.child_fd());
471 close(stdout_pipe.child_fd());
472 close(stderr_pipe.child_fd());
473 make_fd_non_blocking(data_pipe.parent_fd());
474 make_fd_non_blocking(stdout_pipe.parent_fd());
475 make_fd_non_blocking(stderr_pipe.parent_fd());
476 inout_buf = std::unique_ptr<filestreambuf>(new filestreambuf(data_pipe.parent_fd(), stdout_pipe.parent_fd()));
477 err_buf = std::unique_ptr<filestreambuf>(new filestreambuf(stderr_pipe.parent_fd(), stdout_pipe.parent_fd()));
478 iosub.rdbuf(inout_buf.get());

Callers

nothing calls this directly

Calls 8

accessFunction · 0.85
errorClass · 0.85
make_fd_non_blockingFunction · 0.85
child_fdMethod · 0.80
parent_fdMethod · 0.80
closeMethod · 0.45
strMethod · 0.45
getMethod · 0.45

Tested by

no test coverage detected