summaryrefslogtreecommitdiffstats
path: root/winpr/libwinpr/utils/test/TestMessagePipe.c
blob: c5a3ee2a6936d690b95cd1fbc5eed60cd86902aa (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include <winpr/crt.h>
#include <winpr/thread.h>
#include <winpr/collections.h>

static DWORD WINAPI message_echo_pipe_client_thread(LPVOID arg)
{
	int index = 0;
	wMessagePipe* pipe = (wMessagePipe*)arg;

	while (index < 100)
	{
		wMessage message = { 0 };
		int count = -1;

		if (!MessageQueue_Post(pipe->In, NULL, 0, (void*)(size_t)index, NULL))
			break;

		if (!MessageQueue_Wait(pipe->Out))
			break;

		if (!MessageQueue_Peek(pipe->Out, &message, TRUE))
			break;

		if (message.id == WMQ_QUIT)
			break;

		count = (int)(size_t)message.wParam;

		if (count != index)
			printf("Echo count mismatch: Actual: %d, Expected: %d\n", count, index);

		index++;
	}

	MessageQueue_PostQuit(pipe->In, 0);

	return 0;
}

static DWORD WINAPI message_echo_pipe_server_thread(LPVOID arg)
{
	wMessage message = { 0 };
	wMessagePipe* pipe = (wMessagePipe*)arg;

	while (MessageQueue_Wait(pipe->In))
	{
		if (MessageQueue_Peek(pipe->In, &message, TRUE))
		{
			if (message.id == WMQ_QUIT)
				break;

			if (!MessageQueue_Dispatch(pipe->Out, &message))
				break;
		}
	}

	return 0;
}

int TestMessagePipe(int argc, char* argv[])
{
	HANDLE ClientThread = NULL;
	HANDLE ServerThread = NULL;
	wMessagePipe* EchoPipe = NULL;
	int ret = 1;

	WINPR_UNUSED(argc);
	WINPR_UNUSED(argv);

	if (!(EchoPipe = MessagePipe_New()))
	{
		printf("failed to create message pipe\n");
		goto out;
	}

	if (!(ClientThread =
	          CreateThread(NULL, 0, message_echo_pipe_client_thread, (void*)EchoPipe, 0, NULL)))
	{
		printf("failed to create client thread\n");
		goto out;
	}

	if (!(ServerThread =
	          CreateThread(NULL, 0, message_echo_pipe_server_thread, (void*)EchoPipe, 0, NULL)))
	{
		printf("failed to create server thread\n");
		goto out;
	}

	WaitForSingleObject(ClientThread, INFINITE);
	WaitForSingleObject(ServerThread, INFINITE);

	ret = 0;

out:
	if (EchoPipe)
		MessagePipe_Free(EchoPipe);
	if (ClientThread)
		CloseHandle(ClientThread);
	if (ServerThread)
		CloseHandle(ServerThread);

	return ret;
}