sfxd/src/sfxc.c

92 lines
2.6 KiB
C

#include "common.h"
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <sys/select.h>
struct sockaddr_un sa_server, sa_client;
void cleanup(void) {
fprintf(stderr, "[client:dbg] Removing receiving socket.\n");
if (sa_client.sun_path[0] != '\0') {
unlink(sa_client.sun_path);
}
}
void on_sigint(int sig) {
(void)sig;
cleanup();
}
int main(int argc, char **argv) {
int sock_fd;
static char buffer[BUFFER_SIZE];
EXPECT(sock_fd = socket(AF_UNIX, SOCK_DGRAM, 0), > 0);
signal(SIGINT, on_sigint);
atexit(cleanup);
memset(&sa_server, 0, sizeof(sa_server));
memset(&sa_client, 0, sizeof(sa_client));
sa_server.sun_family = sa_client.sun_family = AF_UNIX;
snprintf(sa_client.sun_path, sizeof(sa_client.sun_path), CLIENT_SOCKET_PATH, (long)getpid());
strncpy(sa_server.sun_path, DAEMON_SOCKET_PATH, sizeof(sa_server.sun_path) - 1);
EXPECT(bind(sock_fd, (struct sockaddr *)&sa_client, sizeof(struct sockaddr_un)), == 0);
if (argc == 1) {
fprintf(stderr, "[client:inf] You're in the interactive mode. Press Ctrl+C or Ctrl+D to exit.\n");
struct timeval timeout;
fd_set fds;
int retval, data_len;
while (1) {
timeout.tv_sec = 1;
timeout.tv_usec = 0;
FD_ZERO(&fds);
FD_SET(STDIN_FILENO, &fds);
FD_SET(sock_fd, &fds);
EXPECT(retval = select(sock_fd + 1, &fds, 0, 0, &timeout), != -1);
if (retval > 0) {
if (FD_ISSET(STDIN_FILENO, &fds)) {
EXPECT(data_len = read(STDIN_FILENO, buffer, BUFFER_SIZE), != -1);
if (data_len == 0) {
break;
}
buffer[data_len - 1] = '\0';
EXPECT(sendto(sock_fd, buffer, strlen(buffer), 0, (struct sockaddr *)&sa_server, sizeof(sa_server)), == (ssize_t)strlen(buffer));
}
if (FD_ISSET(sock_fd, &fds)) {
while ((data_len = recv(sock_fd, buffer, BUFFER_SIZE, 0)) > 0) {
printf("%.*s", data_len, buffer);
}
}
}
}
} else {
for (int i = 1; i < argc; i++) {
strncat(buffer, argv[i], BUFFER_SIZE - strlen(buffer) - 1);
if (i != argc - 1) {
strncat(buffer, " ", BUFFER_SIZE - strlen(buffer) - 1);
}
}
printf("send: '%s'\n", buffer);
EXPECT(sendto(sock_fd, buffer, strlen(buffer), 0, (struct sockaddr *)&sa_server, sizeof(sa_server)), == (ssize_t)strlen(buffer));
int data_len;
while ((data_len = recv(sock_fd, buffer, BUFFER_SIZE, 0)) > 0) {
printf("%.*s", data_len, buffer);
}
}
exit(EXIT_SUCCESS);
}