int util_create_lock_file(const char *lockFileName, bool abortDuplicates) { int result = 0; FILE *fp = safe_fopen_wrapper_follow( lockFileName, "w" ); if ( fp == NULL ) { debug_printf( DEBUG_QUIET, "ERROR: could not open lock file %s for writing.\n", lockFileName); result = -1; } // // Create the ProcessId object. // ProcessId *procId = NULL; if ( result == 0 && abortDuplicates ) { int status; int precision_range = 1; if ( ProcAPI::createProcessId( daemonCore->getpid(), procId, status, &precision_range ) != PROCAPI_SUCCESS ) { debug_printf( DEBUG_QUIET, "ERROR: ProcAPI::createProcessId() " "failed; %d\n", status ); result = -1; } } // // Write out the ProcessId object. // if ( result == 0 && abortDuplicates ) { if ( procId->write( fp ) != ProcessId::SUCCESS ) { debug_printf( DEBUG_QUIET, "ERROR: ProcessId::write() failed\n"); result = -1; } } // // Sleep to ensure uniqueness of the ProcessId object. // if ( result == 0 && abortDuplicates ) { const int maxSleepTime = 60; // seconds; arbitrarily chosen int sleepTime = procId->computeWaitTime(); if ( sleepTime > maxSleepTime ) { debug_printf( DEBUG_QUIET, "Warning: ProcessId computed sleep " "time (%d) exceeds maximum (%d); skipping sleep/" "confirm step\n", sleepTime, maxSleepTime ); check_warning_strictness( DAG_STRICT_3 ); } else { debug_printf( DEBUG_NORMAL, "Sleeping for %d seconds to " "ensure ProcessId uniqueness\n", sleepTime ); #if defined(WIN32) sleep( sleepTime ); #else while( (sleepTime = sleep( sleepTime ) ) != 0 ) { } #endif // // Confirm the ProcessId object's uniqueness. // int status; if ( ProcAPI::confirmProcessId( *procId, status ) != PROCAPI_SUCCESS ) { debug_printf( DEBUG_QUIET, "Warning: ProcAPI::" "confirmProcessId() failed; %d\n", status ); check_warning_strictness( DAG_STRICT_3 ); } else { if ( !procId->isConfirmed() ) { debug_printf( DEBUG_QUIET, "Warning: ProcessId not " "confirmed unique\n" ); check_warning_strictness( DAG_STRICT_3 ); } else { // // Write out the confirmation. // if ( procId->writeConfirmationOnly( fp ) != ProcessId::SUCCESS ) { debug_printf( DEBUG_QUIET, "ERROR: ProcessId::" "writeConfirmationOnly() failed\n"); result = -1; } } } } } delete procId; if ( fp != NULL ) { if ( fclose( fp ) != 0 ) { debug_printf( DEBUG_QUIET, "ERROR: closing lock " "file failed with errno %d (%s)\n", errno, strerror( errno ) ); } } return result; }