Newer
Older
access-test / modules / src / test_lock.c
Nomura Kei on 5 Dec 2022 1 KB update
/**
 * @file	test_lock.c
 * @brief	lock テスト
 * @author	Nomura Kei
 * @copyright 2008  Nomura Kei
 */
#include <stdio.h>
#include <errno.h>

#include <sys/file.h>

#include <filetype.h>
#include <test_lock.h>


/**
 * 指定されたパスをロックします。
 * 指定されたパスが存在しない場合は、errno に ENOENT が設定され、false を返します。
 *
 * @param pathname パス
 * @param is_share (true/false) 共有ロック/排他ロック
 * @return true/false (生成成功/生成失敗)
 */
bool can_lock(const char* pathname, bool is_share)
{
	// パス存在有無確認 (しない場合 NG)
	bool is_error = !is_exists(pathname);
	if (is_error)
	{
		errno = ENOENT;
		return false;
	}

	// fd 取得
	int fd = open(pathname, O_RDONLY);
	if (fd == -1)
	{
		fd = open(pathname, O_WRONLY);
		if (fd == -1)
		{
			return false;
		}
	}

	int lock_type = (is_share) ? LOCK_SH : LOCK_EX;
	int ret = flock(fd, lock_type);
	bool is_success = (ret == 0);
	if (is_success)
	{
		flock(fd, LOCK_UN);
	}
	return is_success;
}