#!ruby # -*- mode: ruby; coding: utf-8 -*- # Last updated: <2022/08/17 02:06:34 +0900> # # win32api sample. use mutex. # # 二重起動の防止(1) - Advanced HSP # http://chokuto.ifdef.jp/advanced/singleton1.html # # Windows10 x64 21H2 + Ruby 1.8.7 p330 i386-mswin32 require "Win32API" create_mutex = Win32API.new("kernel32", "CreateMutex", "llp", "l") release_mutex = Win32API.new("kernel32", "ReleaseMutex", "l", "l") close_handle = Win32API.new("kernel32", "CloseHandle", "l", "l") get_last_error = Win32API.new("kernel32", "GetLastError", "", "l") MUTEX_NAME = "ruby_win32api_mutex_sample" ERROR_ALREADY_EXISTS = 183 mutex = create_mutex.call(0, 1, MUTEX_NAME) err = get_last_error.call() puts "Mutex : #{mutex}" puts "GetLastError : #{err}" if mutex == 0 or err == ERROR_ALREADY_EXISTS puts "already exists" exit else 10.times do |i| puts i sleep 1 end end if mutex != 0 release_mutex.call(mutex) close_handle.call(mutex) end