Zijie He | 825f65e | 2017-08-16 14:56:42 -0700 | [diff] [blame] | 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 | |
Mirko Bonadei | 92ea95e | 2017-09-15 06:47:31 +0200 | [diff] [blame] | 11 | #include "modules/desktop_capture/screen_drawer_lock_posix.h" |
Zijie He | 825f65e | 2017-08-16 14:56:42 -0700 | [diff] [blame] | 12 | |
| 13 | #include <fcntl.h> |
| 14 | #include <sys/stat.h> |
| 15 | |
Mirko Bonadei | 92ea95e | 2017-09-15 06:47:31 +0200 | [diff] [blame] | 16 | #include "rtc_base/checks.h" |
| 17 | #include "rtc_base/logging.h" |
Zijie He | 825f65e | 2017-08-16 14:56:42 -0700 | [diff] [blame] | 18 | |
| 19 | namespace webrtc { |
| 20 | |
| 21 | namespace { |
| 22 | |
| 23 | // A uuid as the name of semaphore. |
| 24 | static constexpr char kSemaphoreName[] = "GSDL54fe5552804711e6a7253f429a"; |
| 25 | |
| 26 | } // namespace |
| 27 | |
| 28 | ScreenDrawerLockPosix::ScreenDrawerLockPosix() |
| 29 | : ScreenDrawerLockPosix(kSemaphoreName) {} |
| 30 | |
| 31 | ScreenDrawerLockPosix::ScreenDrawerLockPosix(const char* name) { |
| 32 | semaphore_ = sem_open(name, O_CREAT, S_IRWXU | S_IRWXG | S_IRWXO, 1); |
| 33 | if (semaphore_ == SEM_FAILED) { |
Mirko Bonadei | 675513b | 2017-11-09 11:09:25 +0100 | [diff] [blame] | 34 | RTC_LOG_ERRNO(LS_ERROR) << "Failed to create named semaphore with " << name; |
Zijie He | 825f65e | 2017-08-16 14:56:42 -0700 | [diff] [blame] | 35 | RTC_NOTREACHED(); |
| 36 | } |
| 37 | |
| 38 | sem_wait(semaphore_); |
| 39 | } |
| 40 | |
| 41 | ScreenDrawerLockPosix::~ScreenDrawerLockPosix() { |
| 42 | if (semaphore_ == SEM_FAILED) { |
| 43 | return; |
| 44 | } |
| 45 | |
| 46 | sem_post(semaphore_); |
| 47 | sem_close(semaphore_); |
| 48 | // sem_unlink a named semaphore won't wait until other clients to release the |
| 49 | // sem_t. So if a new process starts, it will sem_open a different kernel |
| 50 | // object with the same name and eventually breaks the cross-process lock. |
| 51 | } |
| 52 | |
| 53 | // static |
| 54 | void ScreenDrawerLockPosix::Unlink(const char* name) { |
| 55 | sem_unlink(name); |
| 56 | } |
| 57 | |
| 58 | } // namespace webrtc |