github.com/jlowellwofford/u-root@v1.0.0/xcmds/run/tempfile.go (about)

     1  // Copyright 2014-2017 the u-root Authors. All rights reserved
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package main
     6  
     7  // ah well, the tempfile in go has a bad limitation. So let's do better.
     8  
     9  import (
    10  	"fmt"
    11  	"os"
    12  	"path/filepath"
    13  	"strconv"
    14  	"sync"
    15  	"time"
    16  )
    17  
    18  // Random number state.
    19  // We generate random temporary file names so that there's a good
    20  // chance the file doesn't exist yet - keeps the number of tries in
    21  // TempFile to a minimum.
    22  var rand uint32
    23  var randmu sync.Mutex
    24  
    25  func reseed() uint32 {
    26  	return uint32(time.Now().UnixNano() + int64(os.Getpid()))
    27  }
    28  
    29  func nextSuffix() string {
    30  	randmu.Lock()
    31  	r := rand
    32  	if r == 0 {
    33  		r = reseed()
    34  	}
    35  	r = r*1664525 + 1013904223 // constants from Numerical Recipes
    36  	rand = r
    37  	randmu.Unlock()
    38  	return strconv.Itoa(int(1e9 + r%1e9))[1:]
    39  }
    40  
    41  // TempFile creates a new temporary file in the directory dir
    42  // with a name beginning with prefix, opens the file for reading
    43  // and writing, and returns the resulting *os.File.
    44  // If dir is the empty string, TempFile uses the default directory
    45  // for temporary files (see os.TempDir).
    46  // Multiple programs calling TempFile simultaneously
    47  // will not choose the same file.  The caller can use f.Name()
    48  // to find the pathname of the file.  It is the caller's responsibility
    49  // to remove the file when no longer needed.
    50  func TempFile(dir, format string) (f *os.File, err error) {
    51  	if dir == "" {
    52  		dir = os.TempDir()
    53  	}
    54  
    55  	nconflict := 0
    56  	for i := 0; i < 10000; i++ {
    57  		name := fmt.Sprintf(format, nextSuffix())
    58  		name = filepath.Join(dir, name)
    59  		f, err = os.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
    60  		if os.IsExist(err) {
    61  			if nconflict++; nconflict > 10 {
    62  				rand = reseed()
    63  			}
    64  			continue
    65  		}
    66  		break
    67  	}
    68  	return
    69  }