/** Generate a filename unique in an NFS namespace by creating a copy of str and appending .{hostname}.{pid} to it. If gethostname() fails then a pseudo- random string is substituted for {hostname} - the randomness of the string should be strong enough across different machines. The main assumption though is that gethostname will not fail and this is just a "safe enough" fallback. The memory returned should be freed using free(). */ static std::string gen_unique_nfs_filename( const char *filename ) { char hostname[HOST_NAME_MAX + 1]; char pid_str[256]; snprintf(pid_str, sizeof pid_str, "%ld", (long)getpid()); if ( gethostname( hostname, sizeof hostname ) != 0 ) { sprint_rand_digits( hostname, HOST_NAME_MAX ); } std::string newname(filename); newname.push_back('.'); newname.append(hostname); newname.push_back('.'); newname.append(pid_str); return newname; }
/** Generate a filename unique in an NFS namespace by creating a copy of str and appending .{hostname}.{pid} to it. If gethostname() fails then a pseudo- random string is substituted for {hostname} - the randomness of the string should be strong enough across different machines. The main assumption though is that gethostname will not fail and this is just a "safe enough" fallback. The memory returned should be freed using free(). */ static char *gen_unique_nfs_filename( const char *filename ) { int pidlen, hnlen, orglen = strlen( filename ); char hostname[HOST_NAME_MAX + 1]; char *newname; if ( gethostname( hostname, HOST_NAME_MAX + 1 ) == 0 ) { hnlen = strlen( hostname ); } else { hnlen = sprint_rand_digits( hostname, HOST_NAME_MAX ); hostname[hnlen] = '\0'; } newname = malloc( orglen + 1 /* period */ + hnlen + 1 /* period */ + /* max possible pid size: 0.31 ~= log(10)2 */ (int)(0.31 * sizeof(pid_t) * CHAR_BIT + 1) + 1 /* '\0' */ ); if ( newname == NULL ) { debug( 1, L"gen_unique_nfs_filename: %s", strerror( errno ) ); return newname; } memcpy( newname, filename, orglen ); newname[orglen] = '.'; memcpy( newname + orglen + 1, hostname, hnlen ); newname[orglen + 1 + hnlen] = '.'; pidlen = sprint_pid_t( getpid(), newname + orglen + 1 + hnlen + 1 ); newname[orglen + 1 + hnlen + 1 + pidlen] = '\0'; /* debug( 1, L"gen_unique_nfs_filename returning with: newname = \"%s\"; " L"HOST_NAME_MAX = %d; hnlen = %d; orglen = %d; " L"sizeof(pid_t) = %d; maxpiddigits = %d; malloc'd size: %d", newname, (int)HOST_NAME_MAX, hnlen, orglen, (int)sizeof(pid_t), (int)(0.31 * sizeof(pid_t) * CHAR_BIT + 1), (int)(orglen + 1 + hnlen + 1 + (int)(0.31 * sizeof(pid_t) * CHAR_BIT + 1) + 1) ); */ return newname; }