Skip to content

Commit beb78b1

Browse files
committed
Use proper tempfiles in {de,}serialize
Serialization was broken/errored due to always using the same fixed file name for the temporary pickle files. This is a problem in setups where multiple instances of XCSF run in parallel (e.g. on Slurm clusters).
1 parent d8353dc commit beb78b1

File tree

1 file changed

+19
-4
lines changed

1 file changed

+19
-4
lines changed

xcsf/pybind_wrapper.cpp

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -649,8 +649,15 @@ class XCS
649649
py::bytes
650650
serialize() const
651651
{
652-
// Write XCSF to a temporary binary file
653-
const char *filename = "_tmp_pickle.bin";
652+
// Create a unique temporary file in /tmp. The file name is made unique
653+
// in place by mkstemp.
654+
char filename[] = "/tmp/xcsf_pickle_XXXXXX";
655+
int fd = mkstemp(filename);
656+
if (fd == -1) {
657+
throw std::runtime_error("Failed to create temporary file in serialize");
658+
}
659+
close(fd);
660+
654661
xcsf_save(&xcs, filename);
655662
// Read the binary file into bytes
656663
std::ifstream file(filename, std::ios::binary);
@@ -673,8 +680,16 @@ class XCS
673680
static XCS
674681
deserialize(const py::bytes &state)
675682
{
676-
// Write the XCSF bytes to a temporary binary file
677-
const char *filename = "_tmp_pickle.bin";
683+
// Create a unique temporary file in /tmp. The file name is made unique
684+
// in place by mkstemp.
685+
char filename[] = "/tmp/xcsf_pickle_XXXXXX";
686+
int fd = mkstemp(filename);
687+
if (fd == -1) {
688+
throw std::runtime_error("Failed to create temporary file in deserialize");
689+
}
690+
close(fd);
691+
692+
// Write the XCSF bytes to the temporary file.
678693
std::ofstream file(filename, std::ios::binary);
679694
file.write(state.cast<std::string>().c_str(),
680695
state.cast<std::string>().size());

0 commit comments

Comments
 (0)