1
|
1 |
#include <assert.h>
|
|
2 |
#include <sys/types.h>
|
|
3 |
#include <sys/socket.h>
|
|
4 |
#include <sys/un.h>
|
|
5 |
#include <errno.h>
|
3
|
6 |
#include <stdlib.h>
|
9
|
7 |
#include <stdio.h>
|
3
|
8 |
|
|
9 |
#include "main.h"
|
1
|
10 |
|
|
11 |
extern int server_socket;
|
|
12 |
|
|
13 |
int try_connect(int s)
|
|
14 |
{
|
2
|
15 |
struct sockaddr_un addr;
|
|
16 |
int res;
|
1
|
17 |
|
2
|
18 |
addr.sun_family = AF_UNIX;
|
|
19 |
strcpy(addr.sun_path, "/tmp/prova.socket");
|
1
|
20 |
|
2
|
21 |
res = connect(s, (struct sockaddr *) &addr, sizeof(addr));
|
|
22 |
return res;
|
1
|
23 |
}
|
|
24 |
|
|
25 |
void wait_server_up()
|
|
26 |
{
|
2
|
27 |
printf("Wait server up\n");
|
|
28 |
sleep(1);
|
1
|
29 |
}
|
|
30 |
|
|
31 |
void fork_server()
|
|
32 |
{
|
2
|
33 |
int pid;
|
1
|
34 |
|
2
|
35 |
/* !!! stdin/stdout */
|
1
|
36 |
|
2
|
37 |
pid = fork();
|
|
38 |
switch (pid)
|
|
39 |
{
|
|
40 |
case 0: /* Child */
|
3
|
41 |
close(server_socket);
|
2
|
42 |
server_main();
|
3
|
43 |
exit(0);
|
2
|
44 |
break;
|
|
45 |
case -1: /* Error */
|
|
46 |
return;
|
|
47 |
default: /* Parent */
|
|
48 |
;
|
|
49 |
}
|
1
|
50 |
}
|
|
51 |
|
|
52 |
int ensure_server_up()
|
|
53 |
{
|
2
|
54 |
int res;
|
1
|
55 |
|
2
|
56 |
server_socket = socket(PF_UNIX, SOCK_STREAM, 0);
|
|
57 |
assert(server_socket != -1);
|
1
|
58 |
|
2
|
59 |
res = try_connect(server_socket);
|
1
|
60 |
|
2
|
61 |
/* Good connection */
|
|
62 |
if (res == 0)
|
|
63 |
return 1;
|
1
|
64 |
|
2
|
65 |
/* If error other than "No one listens on the other end"... */
|
3
|
66 |
if (!(errno == ENOENT || errno == ECONNREFUSED))
|
9
|
67 |
{
|
|
68 |
perror("c: cannot connect to the server");
|
|
69 |
exit(-1);
|
|
70 |
}
|
1
|
71 |
|
3
|
72 |
if (errno == ECONNREFUSED)
|
|
73 |
unlink("/tmp/prova.socket");
|
|
74 |
|
2
|
75 |
/* Try starting the server */
|
|
76 |
fork_server();
|
|
77 |
wait_server_up();
|
|
78 |
res = try_connect(server_socket);
|
1
|
79 |
|
2
|
80 |
/* The second time didn't work. Abort. */
|
|
81 |
if (res == -1)
|
9
|
82 |
{
|
|
83 |
fprintf(stderr, "The server didn't come up.\n");
|
|
84 |
exit(-1);
|
|
85 |
}
|
1
|
86 |
|
2
|
87 |
/* Good connection on the second time */
|
|
88 |
return 1;
|
1
|
89 |
}
|