blob: 4be45d4f4b0b1377c0d34549288c436da660918b [file] [log] [blame]
Ian Barkley-Yeung43947aa2019-04-26 11:38:34 -07001// Copyright 2019 The Chromium OS Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// A simple program that checks if a file (given on the command line) is locked.
6// It is a helper for crash_sender_util_test.cc. It's necessary because a
7// program can't really check if it is holding a lock on a file itself
8// (https://stackoverflow.com/q/55944551/608736).
9// It exits with 0 if the file is locked, 1 if the file is not locked, and
10// a negative exit value if the file can't be found or there are other errors.
11
12#include <stdlib.h>
13
14#include <base/files/file.h>
15#include <base/logging.h>
16#include <brillo/syslog_logging.h>
17
18int main(int argc, char* argv[]) {
19 brillo::InitLog(brillo::kLogToSyslog | brillo::kLogToStderr);
20
21 if (argc != 2) {
22 LOG(ERROR)
23 << "Usage: lock_file_tester file_name.\n"
24 << "Tests to see if file_name is locked by another process. Exit\n"
25 << "status 0 if locked, 1 if not locked.";
26 exit(-1);
27 }
28
29 base::FilePath lock_file_path(argv[1]);
30 base::File lock_file(lock_file_path, base::File::FLAG_OPEN |
31 base::File::FLAG_READ |
32 base::File::FLAG_WRITE);
33 if (!lock_file.IsValid()) {
34 LOG(ERROR) << "Error opening " << lock_file_path.value() << ": "
35 << base::File::ErrorToString(lock_file.error_details());
36 exit(-2);
37 }
38
39 if (lock_file.Lock() == base::File::FILE_OK) {
40 // We could lock the file, therefore no one else had locked it.
41 exit(1);
42 }
43
44 // There is no way in the base::File API to distinguish "file is locked by
45 // another process" vs "A different error occurred", so we treat all failures
46 // as the former.
47 exit(0);
48}