-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmessagec.c
More file actions
93 lines (78 loc) · 2.74 KB
/
Copy pathmessagec.c
File metadata and controls
93 lines (78 loc) · 2.74 KB
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
/*
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* | M e s s a g e C |
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
* messagec.c — message forwarding library demo.
* +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
*/
#include <msgc/msg.h>
#include <stdio.h>
#include <stdlib.h>
#define MSG_PRINT (MSGC_USER + 0)
#define MSG_SHUTDOWN (MSGC_USER + 1)
typedef struct {
const char *name;
int count;
} appctx;
static int on_print(msgc_target *tgt, msgc_msg *msg, void *userdata)
{
(void)tgt;
appctx *ctx = userdata;
ctx->count++;
printf("[%s] print #%d: wparam=%lu lparam=%lu\n",
ctx->name, ctx->count,
(unsigned long)msg->wparam,
(unsigned long)msg->lparam);
return MSGC_OK;
}
static int on_shutdown(msgc_target *tgt, msgc_msg *msg, void *userdata)
{
(void)tgt;
(void)msg;
appctx *ctx = userdata;
printf("[%s] shutting down after %d prints\n", ctx->name, ctx->count);
msgc_postquit(msgc_target_queue(tgt), 0);
return MSGC_OK;
}
int main(int argc, char **argv)
{
(void)argc;
(void)argv;
msgc_queue *q = msgc_queue_create();
if (!q) {
fprintf(stderr, "msgc_queue_create failed\n");
return 1;
}
appctx ctx = {"demo", 0};
msgc_target *printer = msgc_target_create(q, on_print, &ctx);
msgc_target *shutdown = msgc_target_create(q, on_shutdown, &ctx);
if (!printer || !shutdown) {
fprintf(stderr, "msgc_target_create failed\n");
return 1;
}
/* post a few messages asynchronously */
if (msgc_postmsg(printer, MSG_PRINT, 100, 200) != MSGC_OK) goto cleanup;
if (msgc_postmsg(printer, MSG_PRINT, 300, 400) != MSGC_OK) goto cleanup;
if (msgc_postmsg(printer, MSG_PRINT, 500, 600) != MSGC_OK) goto cleanup;
/* sync send — runs handler immediately on this thread */
printf("--- sync send ---\n");
int syncret = msgc_sendmsg(printer, MSG_PRINT, 999, 0);
if (syncret != MSGC_OK) {
fprintf(stderr, "msgc_sendmsg returned %d\n", syncret);
}
/* async post shutdown — will stop the loop after previous messages */
if (msgc_postmsg(shutdown, MSG_SHUTDOWN, 0, 0) != MSGC_OK) goto cleanup;
/* run the message loop */
printf("--- entering loop ---\n");
int exitcode;
int ret = msgc_run(q, &exitcode);
printf("--- loop exited with ret=%d exitcode=%d ---\n", ret, exitcode);
if (ret != MSGC_OK) {
fprintf(stderr, "msgc_run failed: %d\n", ret);
}
cleanup:
msgc_target_destroy(shutdown);
msgc_target_destroy(printer);
msgc_queue_destroy(q);
return (ret == MSGC_OK) ? exitcode : 1;
}