From 0c99600235724a2a48098cfac3541bdfcb6f57f7 Mon Sep 17 00:00:00 2001 From: Jordan Orelli Date: Thu, 3 Jul 2014 22:46:56 +0000 Subject: [PATCH] added a few options --- randomizr.go | 63 ++++++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 54 insertions(+), 9 deletions(-) diff --git a/randomizr.go b/randomizr.go index 38d741c..0ff24b9 100644 --- a/randomizr.go +++ b/randomizr.go @@ -9,7 +9,10 @@ import ( ) var ( - fname string + fname string + fappend bool + reopen bool + freq float64 ) // generates a pseudorandom string of length n that is composed of alphanumeric @@ -27,26 +30,68 @@ func outFile() (*os.File, error) { if fname == "" { return os.Stdout, nil } - options := os.O_WRONLY | os.O_APPEND | os.O_CREATE + options := os.O_WRONLY | os.O_CREATE + if fappend { + options |= os.O_APPEND + } else { + options |= os.O_TRUNC + } + return os.OpenFile(fname, options, 0644) } -func main() { - flag.Parse() +func reopenWrite(c chan string) { + for line := range c { + f, err := outFile() + if err != nil { + fmt.Printf("ERROR: unable to open outfile: %v", err) + continue + } + if _, err := f.WriteString(line); err != nil { + fmt.Printf("ERROR: unable to write line: %v", err) + } + f.Close() + } +} +func regularWrite(c chan string) { f, err := outFile() if err != nil { - fmt.Printf("ERROR: %v\n", err) - os.Exit(1) + fmt.Printf("ERROR: unable to open outfile: %v", err) + return } defer f.Close() - for t := range time.Tick(100 * time.Millisecond) { - fmt.Fprintf(f, "%v %v %v\n", t.UnixNano(), randomString(32), randomString(32)) + for line := range c { + if _, err := f.WriteString(line); err != nil { + fmt.Printf("ERROR: unable to write line: %v", err) + } + } +} + +func writeLines(c chan string) { + if reopen { + go reopenWrite(c) + } else { + go regularWrite(c) + } +} + +func main() { + flag.Parse() + c := make(chan string) + + writeLines(c) + + for t := range time.Tick(time.Duration(1e9 / freq)) { + c <- fmt.Sprintf("%v %v %v\n", t.UnixNano(), randomString(32), randomString(32)) } } func init() { - flag.StringVar(&fname, "file", "", "destination file to which random data will be appended") + flag.StringVar(&fname, "file", "", "destination file to which random data will be written") + flag.BoolVar(&fappend, "append", false, "append to file instead of truncating file on open") + flag.BoolVar(&reopen, "reopen", false, "reopen file handle on every write instead of using a persistent handle") + flag.Float64Var(&freq, "freq", 1, "frequency in hz at which lines will be written") rand.Seed(time.Now().UnixNano()) }