Lindenii Project Forge
Login
Commit info
ID36c43d168d564fe311974efa6f6ac322afcf71d6
AuthorRunxi Yu<me@runxiyu.org>
Author dateMon, 17 Feb 2025 01:51:27 +0800
CommitterRunxi Yu<me@runxiyu.org>
Committer dateMon, 17 Feb 2025 01:51:27 +0800
Actions
Get patch
git_hooks_client: Splice stdin

Requires stdin to be a pipe. So `cat | ./git_hooks_client` works while
`./git_hooks_client` in a terminal directly does not (character devices
are not pipes).
CFLAGS = -Wall -Wextra -Werror -pedantic -std=c99 -D_GNU_SOURCE

git_hooks_client:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <string.h>
#include <fcntl.h>

int main() {
int main(void) {
	int sock;
	struct sockaddr_un addr;
	const char *message = "hi";
	const char *socket_path = getenv("LINDENII_FORGE_HOOKS_SOCKET_PATH");

	if (socket_path == NULL) {
		exit(EXIT_FAILURE);
		return EXIT_FAILURE;
	}

	sock = socket(AF_UNIX, SOCK_STREAM, 0);
	if (sock == -1) {
		perror("socket");
		exit(EXIT_FAILURE);
		return EXIT_FAILURE;
	}

	memset(&addr, 0, sizeof(struct sockaddr_un));
	addr.sun_family = AF_UNIX;
	strncpy(addr.sun_path, socket_path, sizeof(addr.sun_path) - 1);

	if (connect(sock, (struct sockaddr *)&addr, sizeof(struct sockaddr_un)) == -1) {
		perror("connect");
		close(sock);
		exit(EXIT_FAILURE);
		return EXIT_FAILURE;
	}

	ssize_t bytes_spliced;
	while ((bytes_spliced = splice(STDIN_FILENO, NULL, sock, NULL, 1, SPLICE_F_MORE)) > 0) {
	}

	if (send(sock, message, strlen(message), 0) == -1) {
		perror("send");
	if (bytes_spliced == -1) {
		perror("splice");
		close(sock);
		exit(EXIT_FAILURE);
		return EXIT_FAILURE;
	}

	close(sock);

	return 0;
	return EXIT_SUCCESS;
}