Selaa lähdekoodia

A simple time-to-socket-printing server example

This is just so what this would look like, in C.  Turn out higher level
languages do provide a lot of useful things.  However, in this program
it's relatively clear where the program/system boundary is, which is
neat.
Lucas Stadler 9 vuotta sitten
vanhempi
commit
2e7e56f0ee
1 muutettua tiedostoa jossa 85 lisäystä ja 0 poistoa
  1. 85 0
      c/unix-socket.c

+ 85 - 0
c/unix-socket.c

@ -0,0 +1,85 @@
1
#include <errno.h>
2
#include <signal.h>
3
#include <stdio.h>
4
#include <stdlib.h>
5
#include <strings.h>
6
#include <time.h>
7
#include <unistd.h>
8
9
#include <sys/socket.h>
10
#include <sys/un.h>
11
12
#define MSG_LEN 100
13
#define SOCKET_PATH "/tmp/test-socket.sock"
14
15
int sock;
16
17
void cleanup() {
18
	if (close(sock)) {
19
		perror("close");
20
	}
21
22
	if (unlink(SOCKET_PATH)) {
23
		perror("unlink");
24
	}
25
}
26
27
static void handle_signal(int signum) {
28
	switch(signum) {
29
	case SIGINT:
30
		cleanup();
31
		exit(0);
32
	default:
33
		fprintf(stderr, "unhandled signal: %d", signum);
34
		exit(1);
35
	}
36
}
37
38
int main(int argc, char **argv) {
39
	sock = socket(AF_UNIX, SOCK_STREAM, 0);
40
41
	struct sockaddr_un addr;
42
	addr.sun_family = AF_UNIX;
43
	strncpy(addr.sun_path, SOCKET_PATH, sizeof(addr.sun_path) - 1);
44
	if (bind(sock, (struct sockaddr*) &addr, sizeof(addr))) {
45
		perror("bind");
46
		goto err;
47
	}
48
49
	struct sigaction sa;
50
	sa.sa_handler = handle_signal;
51
	sigemptyset(&sa.sa_mask);
52
	sa.sa_flags = SA_RESTART;
53
	if (sigaction(SIGINT, &sa, NULL) < 0) {
54
		perror("sigaction");
55
	}
56
57
	printf("listening on %s\n", SOCKET_PATH);
58
	if (listen(sock, 0) < 0) {
59
		perror("listen");
60
		goto err;
61
	}
62
63
	for (;;) {
64
		int conn = accept(sock, NULL, NULL);
65
		if (conn < 0) {
66
			perror("accept");
67
			goto err;
68
		}
69
70
		char msg[MSG_LEN];
71
		time_t now = time(NULL);
72
		int len = strftime(msg, MSG_LEN, "%Y-%m-%d %H:%M:%S %z\n", localtime(&now));
73
		if (write(conn, msg, len) < 0) {
74
			perror("write");
75
		}
76
77
		if (close(conn) < 0) {
78
			perror("close conn");
79
		}
80
	}
81
82
err:
83
	cleanup();
84
	return 0;
85
}