[Spice-devel] [PATCH spice-streaming-agent] Use RAII to cleanup stream in case of exception or return

Christophe Fergeau cfergeau at redhat.com
Fri Nov 10 10:39:02 UTC 2017


On Thu, Nov 09, 2017 at 06:48:08PM +0100, Christophe de Dinechin wrote:
> From: Christophe de Dinechin <dinechin at redhat.com>
> 
> This lets us get rid of C-style 'goto done' in do_capture.
> 
> Signed-off-by: Christophe de Dinechin <dinechin at redhat.com>
> ---
>  src/spice-streaming-agent.cpp | 34 ++++++++++++++++++++--------------
>  1 file changed, 20 insertions(+), 14 deletions(-)
> 
> diff --git a/src/spice-streaming-agent.cpp b/src/spice-streaming-agent.cpp
> index ed7ddb9..e2719fa 100644
> --- a/src/spice-streaming-agent.cpp
> +++ b/src/spice-streaming-agent.cpp
> @@ -348,17 +348,30 @@ do_capture(const char *streamport, FILE *f_log)
>      if (!capture)
>          throw std::runtime_error("cannot find a suitable capture system");
>  
> -    streamfd = open(streamport, O_RDWR);
> -    if (streamfd < 0)
> -        // TODO was syslog(LOG_ERR, "Failed to open %s: %s\n", streamport, strerror(errno));
> -        throw std::runtime_error("failed to open streaming device");
> +    struct Stream
> +    {
> +        Stream(const char *name, int &fd): fd(fd)
> +        {
> +            fd = open(name, O_RDWR);
> +            if (fd < 0)
> +                throw std::runtime_error("failed to open streaming device");
> +        }
> +        ~Stream()
> +        {
> +            if (fd >= 0)
> +                close(fd);
> +            fd = -1;
> +        }
> +        int &fd;
> +    }
> +    stream(streamport, streamfd);

Honestly, the defer-style syntax was much more readable, rather than
having code moved to some adhoc local class. Either you make this a
proper high-level class wraps open/close for an fd, and we can use it
here, or I prefer to stick to goto/defer.

Christophe
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <https://lists.freedesktop.org/archives/spice-devel/attachments/20171110/b7ac3c21/attachment.sig>


More information about the Spice-devel mailing list