Search code examples
multiprocessingfortranintel-fortran

System-wide unique filename in fortran


I have a fortran program that needs to find the filename that case-insensitively matches 'my_file'

To do this I use the following command:

call system "find -ipath '*my_file' > " // trim(tmp_name)

whereafter I read the contents of tmp_name

When running multiple instances of the program, they fails because all instances write to the same file.

I have not succeeded with the following solutions:

  • obtain output from system without saving to file
  • add random number to filename (does not work as the random numbers are not unique between instances started at the same time, even with CALL RANDOM_INIT (REPEATABLE=.FALSE., IMAGE_DISTINCT=.TRUE.))
  • open a scratch file and then use the name of the file (does not work as the scratch files were not named)
  • run within !$omp critical(critical_generate_temp_name) block

Any ideas?


Solution

  • You can certainly include the PID (process ID) into the file name. Intel Fortran, and some other compilers, have the GETPID() function from the IFPORT module (can be also a non-standard intrinsic in other compilers), but you can also use GET_ENVIRONMENT_VARIABLE() instead and inquire the PID environment variable value (a string that you can append to your file name).

    The PID should be unique at any given time, but will repeat in the future after the original process terminated. (PID reuse possibility in Linux)

    You can also include the date and time.


    This is a quick an dirty pragmatic solution to get the job done quickly that may be insecure in certain multi-user (or already compromised) systems. Other answers with other approaches are welcome.