github.com/blixtra/rkt@v0.8.1-0.20160204105720-ab0d1add1a43/stage1/common/run.go (about)

     1  // Copyright 2015 The rkt Authors
     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 common
    16  
    17  import (
    18  	"errors"
    19  	"fmt"
    20  	"io/ioutil"
    21  	"os"
    22  	"path/filepath"
    23  
    24  	"github.com/coreos/rkt/pkg/sys"
    25  	"github.com/hashicorp/errwrap"
    26  )
    27  
    28  // WithClearedCloExec executes a given function in between setting and unsetting the close-on-exit flag
    29  // on the given file descriptor
    30  func WithClearedCloExec(lfd int, f func() error) error {
    31  	err := sys.CloseOnExec(lfd, false)
    32  	if err != nil {
    33  		return err
    34  	}
    35  	defer sys.CloseOnExec(lfd, true)
    36  
    37  	return f()
    38  }
    39  
    40  // WritePpid writes the pid's parent pid to $PWD/ppid
    41  func WritePpid(pid int) error {
    42  	// write ppid file as specified in
    43  	// Documentation/devel/stage1-implementors-guide.md
    44  	out, err := os.Getwd()
    45  	if err != nil {
    46  		return errwrap.Wrap(errors.New("cannot get current working directory"), err)
    47  	}
    48  	// we are the parent of the process that is PID 1 in the container so we write our PID to "ppid"
    49  	err = ioutil.WriteFile(filepath.Join(out, "ppid"),
    50  		[]byte(fmt.Sprintf("%d\n", pid)), 0644)
    51  	if err != nil {
    52  		return errwrap.Wrap(errors.New("cannot write ppid file"), err)
    53  	}
    54  	return nil
    55  }