Esempio n. 1
1
func work(c *replicant.Client, C <-chan time.Time, stop chan bool, done chan bool, dl *ygor.DataLogger) {
	defer func() {
		done <- true
	}()
	for {
		select {
		case <-C:
			break
		case <-stop:
			return
		}
		start := time.Now()
		_, err := c.Call("echo", "echo", []byte("hello world"), 0)
		end := time.Now()
		if err.Status == replicant.SUCCESS {
			when := uint64(end.UnixNano())
			data := uint64(end.Sub(start).Nanoseconds())
			er := dl.Record(1, when, data)
			if er != nil {
				fmt.Printf("error: %s\n", er)
				os.Exit(1)
			}
		} else {
			fmt.Printf("error: %s\n", err)
			os.Exit(1)
		}
	}
}
Esempio n. 2
0
// NewCmdBuildLogs implements the OpenShift cli build-logs command
func NewCmdBuildLogs(fullName string, f *clientcmd.Factory, out io.Writer) *cobra.Command {
	opts := api.BuildLogOptions{}
	cmd := &cobra.Command{
		Use:        "build-logs BUILD",
		Short:      "Show logs from a build",
		Long:       buildLogsLong,
		Example:    fmt.Sprintf(buildLogsExample, fullName),
		Deprecated: fmt.Sprintf("use \"oc %v build/<build-name>\" instead.", LogsRecommendedCommandName),
		Run: func(cmd *cobra.Command, args []string) {
			err := RunBuildLogs(fullName, f, out, cmd, opts, args)

			if err, ok := err.(errors.APIStatus); ok {
				if msg := err.Status().Message; strings.HasSuffix(msg, buildutil.NoBuildLogsMessage) {
					fmt.Fprintf(out, msg)
					os.Exit(1)
				}
				if err.Status().Code == http.StatusNotFound {
					switch err.Status().Details.Kind {
					case "build":
						fmt.Fprintf(out, "The build %s could not be found.  Therefore build logs cannot be retrieved.\n", err.Status().Details.Name)
					case "pod":
						fmt.Fprintf(out, "The pod %s for build %s could not be found.  Therefore build logs cannot be retrieved.\n", err.Status().Details.Name, args[0])
					}
					os.Exit(1)
				}
			}
			kcmdutil.CheckErr(err)
		},
	}
	cmd.Flags().BoolVarP(&opts.Follow, "follow", "f", true, "Specify whether logs should be followed; default is true.")
	cmd.Flags().BoolVarP(&opts.NoWait, "nowait", "w", false, "Specify whether to return immediately without waiting for logs to be available; default is false.")
	return cmd
}
Esempio n. 3
0
// Build creates a new Route using the specification details collected by the RouteBuilder
func (b *RouteBuilder) Build() Route {
	pathExpr, err := newPathExpression(b.currentPath)
	if err != nil {
		log.Printf("[restful] Invalid path:%s because:%v", b.currentPath, err)
		os.Exit(1)
	}
	if b.function == nil {
		log.Printf("[restful] No function specified for route:" + b.currentPath)
		os.Exit(1)
	}
	operationName := b.operation
	if len(operationName) == 0 && b.function != nil {
		// extract from definition
		operationName = nameOfFunction(b.function)
	}
	route := Route{
		Method:         b.httpMethod,
		PathPrefix:     b.rootPathPrefix,
		Path:           concatPath(b.rootPath, b.currentPath),
		Produces:       b.produces,
		Consumes:       b.consumes,
		Function:       b.function,
		Filters:        b.filters,
		relativePath:   b.currentPath,
		pathExpr:       pathExpr,
		Doc:            b.doc,
		Notes:          b.notes,
		Operation:      operationName,
		ParameterDocs:  b.parameters,
		ResponseErrors: b.errorMap,
		ReadSample:     b.readSample,
		WriteSample:    b.writeSample}
	route.postBuild()
	return route
}
Esempio n. 4
0
// TestLinuxSendfileChild isn't a real test. It's used as a helper process
// for TestLinuxSendfile.
func TestLinuxSendfileChild(*testing.T) {
	if os.Getenv("GO_WANT_HELPER_PROCESS") != "1" {
		return
	}
	defer os.Exit(0)
	fd3 := os.NewFile(3, "ephemeral-port-listener")
	ln, err := net.FileListener(fd3)
	if err != nil {
		panic(err)
	}
	mux := http.NewServeMux()

	fs := &FileServer{
		http.Dir("testdata"),
		inject.CopyInject{},
		ricetemp.MustMakeTemplates(rice.MustFindBox("../templates")),
	}

	mux.Handle("/", fs)
	mux.HandleFunc("/quit", func(http.ResponseWriter, *http.Request) {
		os.Exit(0)
	})
	s := &http.Server{Handler: mux}
	err = s.Serve(ln)
	if err != nil {
		panic(err)
	}
}
func getAppGuid(cliConnection plugin.CliConnection, appName string) string {
	repo := core_config.NewRepositoryFromFilepath(config_helpers.DefaultFilePath(), func(err error) {
		if err != nil {
			fmt.Println("\nERROR:", err)
			os.Exit(1)
		}
	})
	spaceGuid := repo.SpaceFields().Guid

	cmd := []string{"curl", fmt.Sprintf("/v2/spaces/%v/apps?q=name:%v&inline-relations-depth=1", spaceGuid, appName)}
	output, err := cliConnection.CliCommandWithoutTerminalOutput(cmd...)
	if err != nil {
		for _, e := range output {
			fmt.Println(e)
		}
		os.Exit(1)
	}

	search := &Search{}
	if err := json.Unmarshal([]byte(strings.Join(output, "")), &search); err != nil {
		fmt.Println("\nERROR:", err)
		os.Exit(1)
	}

	return search.Resources[0].Metadata.Guid
}
Esempio n. 6
0
func setBash() {
	findcmd := "which"
	if runtime.GOOS == "windows" {
		// Can't use paths returned from which even if it's on PATH in Windows
		// Because our Go binary is a separate Windows app & not MinGW, it
		// can't understand paths like '/usr/bin/bash', needs Windows version
		findcmd = "where"
	}
	out, err := exec.Command(findcmd, "bash").Output()
	if err != nil {
		fmt.Println("Unable to find bash:", err)
		os.Exit(1)
	}

	bashPath = strings.TrimSpace(string(out))
	if debugging {
		fmt.Println("Using", bashPath)
	}

	// Test
	_, err = exec.Command(bashPath, "--version").CombinedOutput()
	if err != nil {
		fmt.Println("Error calling bash:", err)
		os.Exit(1)
	}
}
Esempio n. 7
0
func main() {

	importer, err := New()
	if err != nil {
		fmt.Println(err)
		fmt.Println("Exiting.")
		os.Exit(1)
	}
	if err := importer.CreateIndex(); err != nil {
		fmt.Println(err)
		fmt.Println("Exiting.")
		os.Exit(1)
	}

	if importer.cl.opt.Dir != "" {
		if err = importer.ImportKibana(importer.cl.opt.Dir); err != nil {
			fmt.Println(err)
		}
	} else {
		if importer.cl.opt.URL != "" || importer.cl.opt.File != "" {
			if err = importer.ImportArchive(); err != nil {
				fmt.Println(err)
			}
		}
	}
}
Esempio n. 8
0
func actionUserPasswd(c *cli.Context) {
	api, user := mustUserAPIAndName(c)
	ctx, cancel := context.WithTimeout(context.Background(), client.DefaultRequestTimeout)
	currentUser, err := api.GetUser(ctx, user)
	cancel()
	if currentUser == nil {
		fmt.Fprintln(os.Stderr, err.Error())
		os.Exit(1)
	}
	pass, err := speakeasy.Ask("New password: "******"Error reading password:"******"Password updated\n")
}
Esempio n. 9
0
func main() {
	// 以下读取网卡信息
	Interface, err := net.Interfaces()
	if err != nil {
		panic("未发现网卡地址")
		os.Exit(1)
	}

	handwareAddrs = make(map[string]string, len(Interface))
	for _, inter := range Interface {
		inMAC := strings.ToUpper(inter.HardwareAddr.String())
		handwareAddrs[inMAC] = inMAC
	}

	if len(os.Args) != 2 {
		fmt.Println("为保障安全:请先绑定本机上的网卡地址")
		os.Exit(0)
	}

	addr := os.Args[1]
	h, e := net.ParseMAC(addr)
	if e != nil {
		fmt.Println("为保障安全:请先绑定本机上的网卡地址")
		fmt.Println("方法:client.exe 90-4C-E5-58-7E-FE")
		os.Exit(2)
	}
	inputMAC := strings.ToUpper(h.String())
	if inputMAC != handwareAddrs[inputMAC] {
		fmt.Println("网卡地址不匹配")
		os.Exit(0)
	}
}
Esempio n. 10
0
func TestMain(m *testing.M) {
	if reexec.Init() {
		return
	}

	if err := createController(); err != nil {
		os.Exit(1)
	}
	option := options.Generic{
		"EnableIPForwarding": true,
	}

	genericOption := make(map[string]interface{})
	genericOption[netlabel.GenericData] = option

	err := controller.ConfigureNetworkDriver(bridgeNetType, genericOption)
	if err != nil {
		//m.Fatal(err)
		os.Exit(1)
	}

	libnetwork.SetTestDataStore(controller, datastore.NewCustomDataStore(datastore.NewMockStore()))

	os.Exit(m.Run())
}
Esempio n. 11
0
File: flags.go Progetto: yubo/falcon
func (f *flags_t) Parse(args []string) (err error) {
	for i, arg := range args {
		for _, f := range CommandLine.flags {
			if arg == f.Name {
				CommandLine.Cmd = f
				if err = flag.CommandLine.Parse(args[0:i]); err != nil {
					return
				}
				if err = f.Flag.Parse(args[i+1:]); err != nil {
					return
				}
				if f.h {
					f.Usage()
					os.Exit(0)
				}
			}
		}
	}
	err = flag.CommandLine.Parse(args)
	if CommandLine.h {
		flag.Usage()
		os.Exit(0)
	}
	return
}
Esempio n. 12
0
func main() {
	input := flag.Arg(0)

	if len(input) == 0 {
		fmt.Fprintln(os.Stderr, "Please provide an input file. (amberc input.amber)")
		os.Exit(1)
	}

	cmp := amber.New()
	cmp.PrettyPrint = prettyPrint
	cmp.LineNumbers = lineNumbers

	err := cmp.ParseFile(input)

	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}

	err = cmp.CompileWriter(os.Stdout)

	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}
Esempio n. 13
0
func DFT(dirname string, depth int, str string) string {
	d, err := os.Open(dirname)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	defer d.Close()
	fi, err := d.Readdir(-1)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	for _, fi := range fi {
		if fi.Mode().IsRegular() {
			str = str + fi.Name()
		}
		if fi.IsDir() {
			str = str + fi.Name()
			str = DFT(dirname+fi.Name()+string(filepath.Separator), depth+1, str)
		} else {
			data, _ := ioutil.ReadFile(dirname + fi.Name())
			str = str + string(data)
		}
	}
	return str
}
Esempio n. 14
0
func main(){
	buf, err := ioutil.ReadFile("test.txt") //Reading the file completely
	if err != nil {                          //error check
		fmt.Println(err)
		os.Exit(1)
	}
	data := string(buf) //bytes to string
	if data[0] == '['{
		result,_ :=arrayParser(data)
		final := result.Array
		for _,k := range final {
			fmt.Println(k)

		}
	}else if data[0] =='{' {
		result,_ :=objParser(data)
		fmt.Println(result)
		k := result.getElement()
		fmt.Println(k)
		/*m := k.(map[string]json)
		for a,b := range m{
			fmt.Println("Key:",a,",Value:",b.getElement())

		}

	}*/
	os.Exit(0)
}
Esempio n. 15
0
func main() {

	if len(os.Args) < 2 {
		fmt.Println("please provide an argument for finding the square root")
		os.Exit(1)
	}

	fval, err := strconv.ParseFloat(os.Args[1], 64)

	if err != nil {
		log.Fatal(err)
	}

	if fval < 0.0 {
		fmt.Println("please provide a positive number")
		os.Exit(1)
	}

	fsqrtval := square_root(fval)
	fmt.Printf("iterative square root of %0.8f is %0.8f\n", fval, fsqrtval)

	fsqrtval_recurse := square_root_r(fval, 0, 0)
	fmt.Printf("recursive square root of %0.8f is %0.8f\n", fval, fsqrtval_recurse)

}
Esempio n. 16
0
func setConfigSubcommand(client *rpc.Client, args []string) {
	if err := setConfig(client); err != nil {
		fmt.Fprintf(os.Stderr, "Error setting config\t%s\n", err)
		os.Exit(1)
	}
	os.Exit(0)
}
Esempio n. 17
0
func main() {

	if len(os.Args) != 2 {
		fmt.Fprintf(os.Stderr, "Usage: %s host:port\n", os.Args[0])
		os.Exit(1)
	}

	service := os.Args[1]

	// There may be syntax errors in the address specified
	tcpAddr, err := net.ResolveTCPAddr("tcp4", service)
	checkError(err)

	// The attempt to connect to the remote service may fail.
	// For example, the service requested might not be running,
	// or there may be no such host connected to the network
	conn, err := net.DialTCP("tcp", nil, tcpAddr)
	checkError(err)

	// Although a connection has been established,
	// writes to the service might fail if the connection has died suddenly,
	// or the network times out
	_, err = conn.Write([]byte("HEAD / HTTP/1.0\r\n\r\n"))
	checkError(err)

	// Similarly, the reads might fail
	result, err := ioutil.ReadAll(conn)
	checkError(err)

	fmt.Println(string(result))

	os.Exit(0)
}
Esempio n. 18
0
func logSetup() {
	level, err := log.LevelInt(*f_loglevel)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}

	color := true
	if runtime.GOOS == "windows" {
		color = false
	}

	if *f_log {
		log.AddLogger("stdio", os.Stderr, level, color)
	}

	if *f_logfile != "" {
		err := os.MkdirAll(filepath.Dir(*f_logfile), 0755)
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
		logfile, err := os.OpenFile(*f_logfile, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0660)
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
		log.AddLogger("file", logfile, level, false)
	}
}
func main() {
	optHost := flag.String("host", "localhost", "Hostname")
	optPort := flag.String("port", "0", "Port")
	optProtocol := flag.String("protocol", "tcp", "tcp or udp")
	optLevel := flag.String("level", "warn", "warn of crit")
	flag.Parse()

	if *optPort == "0" {
		fmt.Println("-port is required")
		os.Exit(UNKNOWN)
	}

	var msg string
	target := fmt.Sprintf("%s:%s", *optHost, *optPort)
	_, err := net.Dial(*optProtocol, target)
	if err != nil {
		switch *optLevel {
		case "crit":
			msg = fmt.Sprintf("CRITICAL: %s://%s closed", *optProtocol, target)
			fmt.Println(msg)
			os.Exit(CRITICAL)
		case "warn":
			msg = fmt.Sprintf("WARNING: %s://%s closed", *optProtocol, target)
			fmt.Println(msg)
			os.Exit(WARNING)
		}
	}
	msg = fmt.Sprintf("OK: %s://%s open", *optProtocol, target)
	fmt.Println(msg)
	os.Exit(OK)
}
Esempio n. 20
0
func dsInRun(c *cmdapp.Command, args []string) {
	openLocal(c)
	format := "txt"
	if len(formatFlag) > 0 {
		format = formatFlag
	}
	if len(args) > 0 {
		switch format {
		case "txt":
			for _, fname := range args {
				dsInTxt(c, fname)
			}
		default:
			fmt.Fprintf(os.Stderr, "%s\n", c.ErrStr("format "+format+" unknown"))
			os.Exit(1)
		}
	} else {
		switch format {
		case "txt":
			dsInTxt(c, "")
		default:
			fmt.Fprintf(os.Stderr, "%s\n", c.ErrStr("format "+format+" unknown"))
			os.Exit(1)
		}
	}
	localDB.Exec(jdh.Commit, "", nil)
}
Esempio n. 21
0
File: main.go Progetto: decebal/kit
func main() {
	if err := cfg.Init(cfg.EnvProvider{Namespace: cfgNamespace}); err != nil {
		kit.Println("Unable to initialize configuration")
		os.Exit(1)
	}

	logLevel := func() int {
		ll, err := cfg.Int(cfgLoggingLevel)
		if err != nil {
			return log.NONE
		}
		return ll
	}
	log.Init(os.Stderr, logLevel)

	cfg := mongo.Config{
		Host:     cfg.MustString(cfgMongoHost),
		AuthDB:   cfg.MustString(cfgMongoAuthDB),
		DB:       cfg.MustString(cfgMongoDB),
		User:     cfg.MustString(cfgMongoUser),
		Password: cfg.MustString(cfgMongoPassword),
	}

	if err := db.RegMasterSession("startup", cfg.DB, cfg); err != nil {
		kit.Println("Unable to initialize MongoDB")
		os.Exit(1)
	}

	kit.AddCommand(
		cmdauth.GetCommands(cfg.DB),
		cmddb.GetCommands(cfg.DB),
	)
	kit.Execute()
}
Esempio n. 22
0
func (r *SpecBuilder) BuildSpecs(args []string, additionalArgs []string) {
	r.commandFlags.computeNodes()

	suites, _ := findSuites(args, r.commandFlags.Recurse, r.commandFlags.SkipPackage, false)

	if len(suites) == 0 {
		complainAndQuit("Found no test suites")
	}

	passed := true
	for _, suite := range suites {
		runner := testrunner.New(suite, 1, false, r.commandFlags.Race, r.commandFlags.Cover, r.commandFlags.CoverPkg, r.commandFlags.Tags, nil)
		fmt.Printf("Compiling %s...\n", suite.PackageName)

		path, _ := filepath.Abs(filepath.Join(suite.Path, fmt.Sprintf("%s.test", suite.PackageName)))
		err := runner.CompileTo(path)
		if err != nil {
			fmt.Println(err.Error())
			passed = false
		} else {
			fmt.Printf("    compiled %s.test\n", suite.PackageName)
		}

		runner.CleanUp()
	}

	if passed {
		os.Exit(0)
	}
	os.Exit(1)
}
Esempio n. 23
0
func TestMain(m *testing.M) {
	var logLevel log.LogLevel

	logLevel = 0
	// logLevel = 1
	// logLevel = 3

	log.SetLoggers(logLevel, os.Stdout, os.Stderr)

	if err := testsInit(); err != nil {
		logger.Errorln(err)
		os.Exit(1)
	}

	exitCode := m.Run()

	if os.Getenv("TEST_IN_CIRCLE") != "true" {
		if err := testsTearDown(); err != nil {
			logger.Errorln(err)
			log.Flush()
			os.Exit(1)
		}
	}

	os.Exit(exitCode)
}
Esempio n. 24
0
func main() {
	if len(os.Args) < 2 {
		fmt.Fprintf(os.Stderr, "USAGE: %v <syntax.asn1> [<syntax2.asn1> ...] \n", "parse-test")
		os.Exit(1)
	}

	asn1.Debug = true
	var defs asn1.Definitions

	for _, arg := range os.Args[1:] {
		data, err := ioutil.ReadFile(arg)
		if err != nil {
			fmt.Fprintf(os.Stderr, "%v\n", err)
			os.Exit(1)
		}

		err = defs.Parse(string(data))
		if err != nil {
			fmt.Fprintf(os.Stderr, "%v\n", err)
			os.Exit(1)
		}
	}

	names := defs.ValueNames()
	sort.Strings(names)
	for _, valuename := range names {
		v, err := defs.Value(valuename)
		if err != nil {
			fmt.Fprintf(os.Stderr, "%v\n", err)
			os.Exit(1)
		}

		fmt.Fprintf(os.Stdout, "%v = %v\n", valuename, v.String())
	}
}
func main() {
	// use os.Args instead of "flags" because "flags" will mess up the man pages!
	path := "rel-eng/completions/bash/"
	if len(os.Args) == 2 {
		path = os.Args[1]
	} else if len(os.Args) > 2 {
		fmt.Fprintf(os.Stderr, "usage: %s [output directory]\n", os.Args[0])
		os.Exit(1)
	}

	outDir, err := OutDir(path)
	if err != nil {
		fmt.Fprintf(os.Stderr, "failed to get output directory: %v\n", err)
		os.Exit(1)
	}
	outFile_openshift := outDir + "openshift"
	openshift := openshift.NewCommandOpenShift("openshift")
	openshift.GenBashCompletionFile(outFile_openshift)

	outFile_osc := outDir + "oc"
	oc := cli.NewCommandCLI("oc", "openshift cli")
	oc.GenBashCompletionFile(outFile_osc)

	outFile_osadm := outDir + "oadm"
	oadm := admin.NewCommandAdmin("oadm", "openshift admin", ioutil.Discard)
	oadm.GenBashCompletionFile(outFile_osadm)
}
Esempio n. 26
0
func main() {
	flag.Usage = Usage
	flag.Parse()

	if *port == "" || *remote == "" {
		flag.Usage()
		os.Exit(1)
	}

	if !*skipVerCheck {
		if vercheck.HasMinorUpdate(
			"https://raw.github.com/ciju/gotunnel/master/VERSION",
			"./VERSION",
		) {
			l.Info("\nNew version of Gotunnel is available. Please update your code and run again. Or start with option -sc to continue with this version.\n")
			os.Exit(0)
		}
	}

	servInfo := make(chan string)

	go func() {
		serverat := <-servInfo
		fmt.Printf("Your site should be available at: \033[1;34m%s\033[0m\n", serverat)
	}()

	if !gtclient.SetupClient(*port, *remote, *subdomain, servInfo) {
		flag.Usage()
		os.Exit(1)
	} else {
		os.Exit(0)
	}
}
Esempio n. 27
0
func initDir(args *argContainer) {
	err := checkDirEmpty(args.cipherdir)
	if err != nil {
		fmt.Printf("Invalid cipherdir: %v\n", err)
		os.Exit(ERREXIT_INIT)
	}

	// Create gocryptfs.conf
	cryptfs.Info.Printf("Choose a password for protecting your files.\n")
	password := readPasswordTwice(args.extpass)
	err = cryptfs.CreateConfFile(args.config, password, args.plaintextnames, args.scryptn)
	if err != nil {
		fmt.Println(err)
		os.Exit(ERREXIT_INIT)
	}

	if args.diriv && !args.plaintextnames {
		// Create gocryptfs.diriv in the root dir
		err = cryptfs.WriteDirIV(args.cipherdir)
		if err != nil {
			fmt.Println(err)
			os.Exit(ERREXIT_INIT)
		}
	}

	cryptfs.Info.Printf(colorGreen + "The filesystem has been created successfully.\n" + colorReset)
	cryptfs.Info.Printf(colorGrey+"You can now mount it using: %s %s MOUNTPOINT\n"+colorReset,
		PROGRAM_NAME, args.cipherdir)
	os.Exit(0)
}
Esempio n. 28
0
// Create a new DNS info provider.
func ExampleNewDNSInfoProvider() {

	// create a DNS client
	credentials := APICredentials{"*****@*****.**", "ApItOken"}
	dnsClient, clientError := NewDNSClient(credentials)
	if clientError != nil {
		fmt.Fprintf(os.Stderr, "Unable to create DNS client: %s", clientError.Error())
		os.Exit(1)
	}

	// create a new DNS info provider instance
	dnsInfoProvider := NewDNSInfoProvider(dnsClient)

	// get all domain names
	domainNames, domainNamesError := dnsInfoProvider.GetDomainNames()
	if domainNamesError != nil {
		fmt.Fprintf(os.Stderr, "Unable to fetch domain names: %s", domainNamesError.Error())
		os.Exit(1)
	}

	// print a list all domain names
	for _, domainName := range domainNames {
		fmt.Fprintf(os.Stdout, "%s\n", domainName)
	}
}
Esempio n. 29
0
File: main.go Progetto: rdallman/t
func main() {
	flag.Parse()
	narg := flag.NArg()
	args := flag.Args()
	if narg < 1 {
		usage()
		os.Exit(1)
	}

	pat := args[0]

	// get file infos to make sure we only have real files
	files, errc := gatherFiles(args[1:])
	go func() {
		err := <-errc
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
	}()

	pres := preBmBc(pat)
	for f := range files {
		// TODO concurrent pipeline
		txt, err := ioutil.ReadFile(f)
		if err != nil {
			continue // TODO err chan ?
		}
		// TODO concurrent pipeline
		found := search(pat, string(txt), pres)
		pnt(f, string(txt), found, 0)
	}
}
Esempio n. 30
0
func daemon(nochdir, noclose int) int {
	var ret, ret2 uintptr
	var err syscall.Errno

	darwin := runtime.GOOS == "darwin"

	// already a daemon
	if syscall.Getppid() == 1 {
		return 0
	}

	// fork off the parent process
	ret, ret2, err = syscall.RawSyscall(syscall.SYS_FORK, 0, 0, 0)
	if err != 0 {
		return -1
	}

	// failure
	if ret2 < 0 {
		os.Exit(-1)
	}

	// handle exception for darwin
	if darwin && ret2 == 1 {
		ret = 0
	}

	// if we got a good PID, then we call exit the parent process.
	if ret > 0 {
		os.Exit(0)
	}

	/* Change the file mode mask */
	_ = syscall.Umask(0)

	// create a new SID for the child process
	s_ret, s_errno := syscall.Setsid()
	if s_errno != nil {
		log.Printf("Error: syscall.Setsid errno: %d", s_errno)
	}
	if s_ret < 0 {
		return -1
	}

	if nochdir == 0 {
		os.Chdir("/")
	}

	if noclose == 0 {
		f, e := os.OpenFile("/dev/null", os.O_RDWR, 0)
		if e == nil {
			fd := f.Fd()
			syscall.Dup2(int(fd), int(os.Stdin.Fd()))
			syscall.Dup2(int(fd), int(os.Stdout.Fd()))
			syscall.Dup2(int(fd), int(os.Stderr.Fd()))
		}
	}

	return 0
}