Skip to content

Commit

Permalink
Prevent file handles from leaking on failed open. (#67)
Browse files Browse the repository at this point in the history
* Prevent file handles from leaking on failed open.

Since the webcam open function only returns the open fh on success, we need to close
the FH ourselves in the event that the subsequent tests fail.

---------

Co-authored-by: Brian Stark <[email protected]>
  • Loading branch information
bpstark and Brian Stark authored Apr 1, 2024
1 parent f8ddb31 commit d456f6c
Showing 1 changed file with 9 additions and 1 deletion.
10 changes: 9 additions & 1 deletion webcam.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,21 @@ type Control struct {
// Checks if device is a v4l2 device and if it is
// capable to stream video
func Open(path string) (*Webcam, error) {

handle, err := unix.Open(path, unix.O_RDONLY|unix.O_NONBLOCK, 0666)
if err != nil {
return nil, err
}
if handle < 0 {
return nil, fmt.Errorf("failed to open %v", path)
}
// At this point the handle is valid and must be return or closed
success := false // If this is not set true prior to function exit we assume error and close the handle
defer func() {
if !success {
// Since the handle is not returned on error we must close it or leak
unix.Close(handle)
}
}()
fd := uintptr(handle)

supportsVideoCapture, supportsVideoStreaming, err := checkCapabilities(fd)
Expand All @@ -63,6 +70,7 @@ func Open(path string) (*Webcam, error) {
w.fd = fd
w.bufcount = 256
w.pollFds = []unix.PollFd{{Fd: int32(fd), Events: unix.POLLIN}}
success = true
return w, nil
}

Expand Down

0 comments on commit d456f6c

Please sign in to comment.