screenrecord: fix race condition

When pressing ctrl-c immediately after starting screenrecord (after
setting the signal handler, but before gStopRequested is set to false)
the record loop would never exit.
Also delete the target file before recreating it, to avoid multiple
instances of screenrecord writing the same file.

Bug: 30247947
Change-Id: I374c125dac69e75638955680a2a5da81e3b22ffe
diff --git a/cmds/screenrecord/screenrecord.cpp b/cmds/screenrecord/screenrecord.cpp
index 36a7e73..59d5661 100644
--- a/cmds/screenrecord/screenrecord.cpp
+++ b/cmds/screenrecord/screenrecord.cpp
@@ -80,7 +80,7 @@
 static uint32_t gTimeLimitSec = kMaxTimeLimitSec;
 
 // Set by signal handler to stop recording.
-static volatile bool gStopRequested;
+static volatile bool gStopRequested = false;
 
 // Previous signal handler state, restored after first hit.
 static struct sigaction gOrigSigactionINT;
@@ -334,9 +334,6 @@
         return err;
     }
 
-    // This is set by the signal handler.
-    gStopRequested = false;
-
     // Run until we're signaled.
     while (!gStopRequested) {
         size_t bufIndex, offset, size;
@@ -640,6 +637,11 @@
         case FORMAT_MP4: {
             // Configure muxer.  We have to wait for the CSD blob from the encoder
             // before we can start it.
+            err = unlink(fileName);
+            if (err != 0 && errno != ENOENT) {
+                fprintf(stderr, "ERROR: couldn't remove existing file\n");
+                abort();
+            }
             int fd = open(fileName, O_CREAT | O_LARGEFILE | O_TRUNC | O_RDWR, S_IRUSR | S_IWUSR);
             if (fd < 0) {
                 fprintf(stderr, "ERROR: couldn't open file\n");
@@ -718,7 +720,7 @@
     if (muxer != NULL) {
         // If we don't stop muxer explicitly, i.e. let the destructor run,
         // it may hang (b/11050628).
-        muxer->stop();
+        err = muxer->stop();
     } else if (rawFp != stdout) {
         fclose(rawFp);
     }