xref: /aosp_15_r20/external/webrtc/modules/desktop_capture/screen_drawer_lock_posix.cc (revision d9f758449e529ab9291ac668be2861e7a55c2422)
1 /*
2  *  Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
3  *
4  *  Use of this source code is governed by a BSD-style license
5  *  that can be found in the LICENSE file in the root of the source
6  *  tree. An additional intellectual property rights grant can be found
7  *  in the file PATENTS.  All contributing project authors may
8  *  be found in the AUTHORS file in the root of the source tree.
9  */
10 
11 #include "modules/desktop_capture/screen_drawer_lock_posix.h"
12 
13 #include <fcntl.h>
14 #include <sys/stat.h>
15 
16 #include "absl/strings/string_view.h"
17 #include "rtc_base/checks.h"
18 #include "rtc_base/logging.h"
19 
20 namespace webrtc {
21 
22 namespace {
23 
24 // A uuid as the name of semaphore.
25 static constexpr char kSemaphoreName[] = "GSDL54fe5552804711e6a7253f429a";
26 
27 }  // namespace
28 
ScreenDrawerLockPosix()29 ScreenDrawerLockPosix::ScreenDrawerLockPosix()
30     : ScreenDrawerLockPosix(kSemaphoreName) {}
31 
ScreenDrawerLockPosix(const char * name)32 ScreenDrawerLockPosix::ScreenDrawerLockPosix(const char* name) {
33   semaphore_ = sem_open(name, O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO, 1);
34   if (semaphore_ == SEM_FAILED) {
35     RTC_LOG_ERRNO(LS_ERROR) << "Failed to create named semaphore with " << name;
36     RTC_DCHECK_NOTREACHED();
37   }
38 
39   sem_wait(semaphore_);
40 }
41 
~ScreenDrawerLockPosix()42 ScreenDrawerLockPosix::~ScreenDrawerLockPosix() {
43   if (semaphore_ == SEM_FAILED) {
44     return;
45   }
46 
47   sem_post(semaphore_);
48   sem_close(semaphore_);
49   // sem_unlink a named semaphore won't wait until other clients to release the
50   // sem_t. So if a new process starts, it will sem_open a different kernel
51   // object with the same name and eventually breaks the cross-process lock.
52 }
53 
54 // static
Unlink(absl::string_view name)55 void ScreenDrawerLockPosix::Unlink(absl::string_view name) {
56   sem_unlink(std::string(name).c_str());
57 }
58 
59 }  // namespace webrtc
60