|
发表于 2011-9-25 09:40:22
|
显示全部楼层
正好最近写的程序中也要求单实例运行,代码贴给你看看吧。- ......
- #ifdef G_OS_WIN32
- #include <windows.h>
- #include <tlhelp32.h>
- #endif
- gboolean helloworld_is_running (void)
- {
- #ifdef G_OS_UNIX
- const gchar* uconfig_path;
- gchar *path;
- FILE *pf;
- gchar buffer[1024];
- pid_t pid = -1;
- uconfig_path = helloworld_dirs_get_user_config_dir();
- path = g_build_filename (uconfig_path, "helloworld.pid", NULL);
- if (!g_file_test(path, G_FILE_TEST_EXISTS))
- {
- g_free(path);
- return FALSE;
- }
- pf = g_fopen (path, "r");
- if (pf == NULL) {
- g_free(path);
- return FALSE;
- }
- g_free(path);
- if (fgets (buffer, sizeof (buffer), pf) == NULL)
- {
- fclose(pf);
- return FALSE;
- }
- fclose(pf);
- pid = atoi(buffer);
- if (pid == -1 || kill (pid, 0) != 0)
- {
- return FALSE;
- }
- return TRUE;
- #endif
- #ifdef G_OS_WIN32
- BOOL bFlag;
- gint cnt = -1;
- HANDLE hSnapShot = NULL;
- PROCESSENTRY32 procentry;
- // Get a handle to a Toolhelp snapshot of all processes.
- hSnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
- if (hSnapShot == INVALID_HANDLE_VALUE)
- {
- return NULL;
- }
- // Get the first process' information.
- procentry.dwSize = sizeof(PROCESSENTRY32);
- bFlag = Process32First(hSnapShot, &procentry);
- // While there are processes, keep looping.
- while (bFlag) {
- // Did we just bump into an NTVDM?
- if (_stricmp(procentry.szExeFile, g_get_prgname()) == 0) {
- cnt += 1;
- }
- procentry.dwSize = sizeof(PROCESSENTRY32);
- bFlag = Process32Next(hSnapShot, &procentry);
- }
- if (cnt < 1)
- return FALSE;
- else
- return TRUE;
- #endif
- }
复制代码 |
|