screen_drawer_lock_posix.cc (1746B)
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 <semaphore.h> 15 #include <sys/stat.h> 16 17 #include <string> 18 19 #include "absl/strings/string_view.h" 20 #include "rtc_base/checks.h" 21 #include "rtc_base/logging.h" 22 23 namespace webrtc { 24 25 namespace { 26 27 // A uuid as the name of semaphore. 28 constexpr char kSemaphoreName[] = "GSDL54fe5552804711e6a7253f429a"; 29 30 } // namespace 31 32 ScreenDrawerLockPosix::ScreenDrawerLockPosix() 33 : ScreenDrawerLockPosix(kSemaphoreName) {} 34 35 ScreenDrawerLockPosix::ScreenDrawerLockPosix(const char* name) { 36 semaphore_ = sem_open(name, O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO, 1); 37 if (semaphore_ == SEM_FAILED) { 38 RTC_LOG_ERRNO(LS_ERROR) << "Failed to create named semaphore with " << name; 39 RTC_DCHECK_NOTREACHED(); 40 } 41 42 sem_wait(semaphore_); 43 } 44 45 ScreenDrawerLockPosix::~ScreenDrawerLockPosix() { 46 if (semaphore_ == SEM_FAILED) { 47 return; 48 } 49 50 sem_post(semaphore_); 51 sem_close(semaphore_); 52 // sem_unlink a named semaphore won't wait until other clients to release the 53 // sem_t. So if a new process starts, it will sem_open a different kernel 54 // object with the same name and eventually breaks the cross-process lock. 55 } 56 57 // static 58 void ScreenDrawerLockPosix::Unlink(absl::string_view name) { 59 sem_unlink(std::string(name).c_str()); 60 } 61 62 } // namespace webrtc