27.mutex跨进程通信

  • 创建互斥量mutex
    1 HANDLE mutex = CreateMutexA(NULL, TRUE, name);

     

  • 根据id打开mutex
    1 HANDLE mutex = OpenMutexA(MUTEX_ALL_ACCESS,TRUE,name);

     

  • 监听
    1 DWORD res = WaitForSingleObject(mutex, 20000);

     

  • 判断事件
     1 switch (res)
     2     {
     3     case WAIT_OBJECT_0:
     4         printf("收到信号-------");
     5         break;
     6     case WAIT_TIMEOUT:
     7         printf("超时没有收到-------");
     8         break;
     9     case WAIT_ABANDONED:
    10         printf("另外一个进程意外终止-------");
    11         break;
    12     default:
    13         break;
    14 
    15     }

     

mutex.c

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <Windows.h>
 4 
 5 char name[100] = "haihualovefang";
 6 
 7 void main()
 8 {
 9     HANDLE mutex = CreateMutexA(NULL, TRUE, name);
10     printf("创建成功");
11     char ch = getch();
12 
13     ReleaseMutex(mutex);
14     printf("触发互斥量");
15     CloseHandle(mutex);
16 
17 
18 }

wait.c

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <Windows.h>
 4 
 5 char name[100] = "myevent";
 6 
 7 void main()
 8 {
 9     HANDLE event = OpenEventA(EVENT_ALL_ACCESS, TRUE, name);//打开事件
10 
11     if (event == NULL)
12     {
13         printf("打开失败");
14         system("pause");
15         return;
16     }
17     printf("等待-------");
18     DWORD res = WaitForSingleObject(event, 20000);
19     switch (res)
20     {
21     case WAIT_OBJECT_0:
22         printf("收到信号-------");
23         break;
24     case WAIT_TIMEOUT:
25         printf("超时没有收到-------");
26         break;
27     case WAIT_ABANDONED:
28         printf("另外一个进程意外终止-------");
29         break;
30     default:
31         break;
32 
33     }
34     CloseHandle(event);
35 
36 
37 
38 
39     system("pause");
40 }

 

posted @ 2018-02-03 15:26  喵小喵~  阅读(604)  评论(0编辑  收藏  举报