Source file src/cmd/vendor/github.com/google/pprof/internal/driver/tempfile.go

     1  // Copyright 2014 Google Inc. All Rights Reserved.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package driver
    16  
    17  import (
    18  	"fmt"
    19  	"os"
    20  	"path/filepath"
    21  	"sync"
    22  )
    23  
    24  // newTempFile returns a new output file in dir with the provided prefix and suffix.
    25  func newTempFile(dir, prefix, suffix string) (*os.File, error) {
    26  	for index := 1; index < 10000; index++ {
    27  		switch f, err := os.OpenFile(filepath.Join(dir, fmt.Sprintf("%s%03d%s", prefix, index, suffix)), os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666); {
    28  		case err == nil:
    29  			return f, nil
    30  		case !os.IsExist(err):
    31  			return nil, err
    32  		}
    33  	}
    34  	// Give up
    35  	return nil, fmt.Errorf("could not create file of the form %s%03d%s", prefix, 1, suffix)
    36  }
    37  
    38  var tempFiles []string
    39  var tempFilesMu = sync.Mutex{}
    40  
    41  // deferDeleteTempFile marks a file to be deleted by next call to Cleanup()
    42  func deferDeleteTempFile(path string) {
    43  	tempFilesMu.Lock()
    44  	tempFiles = append(tempFiles, path)
    45  	tempFilesMu.Unlock()
    46  }
    47  
    48  // cleanupTempFiles removes any temporary files selected for deferred cleaning.
    49  func cleanupTempFiles() error {
    50  	tempFilesMu.Lock()
    51  	defer tempFilesMu.Unlock()
    52  	var lastErr error
    53  	for _, f := range tempFiles {
    54  		if err := os.Remove(f); err != nil {
    55  			lastErr = err
    56  		}
    57  	}
    58  	tempFiles = nil
    59  	return lastErr
    60  }
    61  

View as plain text