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
|
#include "master.h"
#include <pthread.h>
#include "nanomsg/nn.h"
#include "nanomsg/survey.h"
#include "json-c/json.h"
#include <stdio.h>
#include <unistd.h>
#include <string.h>
static pthread_t master_thread;
static int master_sock;
static int master_must_terminate = 0;
static void *master_func( void *thread_data )
{
char *control = (char *)thread_data;
master_sock = nn_socket( AF_SP, NN_SURVEYOR );
(void)nn_bind( master_sock, control );
printf( "master connected to %s\n", control );
sleep( 1 );
json_object *obj = json_object_new_object( );
json_object *op = json_object_new_string( "discover" );
json_object_object_add( obj, "op", op );
const char *msg = json_object_to_json_string( obj );
int msg_size = strlen( msg ) + 1;
printf( "master send: %s\n", msg );
int bytes = nn_send( master_sock, msg, msg_size, 0 );
if( bytes != msg_size ) {
fprintf( stderr, "ERROR: truncated message!" );
}
json_object_put( obj );
while( !master_must_terminate ) {
printf( "master idle: %d\n", master_must_terminate );
sleep( 1 );
char *answer = NULL;
bytes = nn_recv( master_sock, &answer, NN_MSG, 0 );
if( bytes == ETIMEDOUT ) continue;
if( master_must_terminate ) continue;
if( bytes >= 0 ) {
printf( "master received: %s\n", answer );
nn_freemsg( answer );
}
}
(void)nn_shutdown( master_sock, 0 );
puts( "master disconnected" );
return NULL;
}
int master_init( const char *control )
{
pthread_attr_t attr;
int res;
master_must_terminate = 0;
res = pthread_attr_init( &attr );
if( res != 0 ) {
return 1;
}
res = pthread_create( &master_thread, &attr, master_func, (void *)control );
if( res != 0 ) {
return 1;
}
return 0;
}
void master_terminate( )
{
master_must_terminate = 1;
}
int master_free( )
{
void *result;
int res;
res = pthread_join( master_thread, &result );
if( res != 0 ) {
return 1;
}
return 0;
}
|