(root)/
strace-6.5/
tests/
lock_file.c
       1  /*
       2   * Copyright (c) 2019-2021 The strace developers.
       3   * All rights reserved.
       4   *
       5   * SPDX-License-Identifier: GPL-2.0-or-later
       6   */
       7  
       8  #include "tests.h"
       9  #include "xmalloc.h"
      10  
      11  #include <fcntl.h>
      12  #include <stdio.h>
      13  #include <stdlib.h>
      14  #include <string.h>
      15  #include <unistd.h>
      16  #include <sys/file.h>
      17  
      18  /* Obtain an exclusive lock on dirname(path_name)/lock_name file.  */
      19  int
      20  lock_file_by_dirname(const char *path_name, const char *lock_name)
      21  {
      22  	const char *slash = path_name ? strrchr(path_name, '/') : NULL;
      23  	const int plen = slash ? (int) (slash - path_name) + 1 : 0;
      24  
      25  	char *lock_file = xasprintf("%.*s%s", plen, path_name, lock_name);
      26  
      27  	int lock_fd = open(lock_file, O_RDONLY);
      28  	if (lock_fd < 0)
      29  		perror_msg_and_fail("open: %s", lock_file);
      30  
      31  	if (flock(lock_fd, LOCK_EX))
      32  		perror_msg_and_fail("flock: %s", lock_file);
      33  
      34  	free(lock_file);
      35  
      36  	return lock_fd;
      37  }