added pidfile, hup handling, truncate option

master
Jordan Orelli 11 years ago
parent 0c99600235
commit 6ea315ab11

@ -5,14 +5,17 @@ import (
"fmt"
"math/rand"
"os"
"os/signal"
"syscall"
"time"
)
var (
fname string
fappend bool
ftruncate bool
reopen bool
freq float64
pidfile string
)
// generates a pseudorandom string of length n that is composed of alphanumeric
@ -31,10 +34,10 @@ func outFile() (*os.File, error) {
return os.Stdout, nil
}
options := os.O_WRONLY | os.O_CREATE
if fappend {
options |= os.O_APPEND
} else {
if ftruncate {
options |= os.O_TRUNC
} else {
options |= os.O_APPEND
}
return os.OpenFile(fname, options, 0644)
@ -55,17 +58,26 @@ func reopenWrite(c chan string) {
}
func regularWrite(c chan string) {
hup := make(chan os.Signal, 1)
signal.Notify(hup, syscall.SIGHUP, syscall.SIGUSR1)
START:
f, err := outFile()
if err != nil {
fmt.Printf("ERROR: unable to open outfile: %v", err)
return
}
defer f.Close()
for line := range c {
for {
select {
case line := <-c:
if _, err := f.WriteString(line); err != nil {
fmt.Printf("ERROR: unable to write line: %v", err)
}
case <-hup:
f.Close()
goto START
}
}
}
@ -77,8 +89,21 @@ func writeLines(c chan string) {
}
}
func writePid() {
if pidfile == "" {
return
}
f, err := os.OpenFile(pidfile, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644)
if err != nil {
fmt.Fprintf(os.Stderr, "ERROR unable to open pidfile: %v", err)
return
}
fmt.Fprintf(f, "%d\n", os.Getpid())
}
func main() {
flag.Parse()
writePid()
c := make(chan string)
writeLines(c)
@ -90,8 +115,9 @@ func main() {
func init() {
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.StringVar(&pidfile, "pidfile", "", "file to which a pid is written")
flag.BoolVar(&ftruncate, "truncate", false, "truncate file on opening instead of appending")
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")
flag.Float64Var(&freq, "freq", 10, "frequency in hz at which lines will be written")
rand.Seed(time.Now().UnixNano())
}

Loading…
Cancel
Save