Skip to content

Instantly share code, notes, and snippets.

@mikdusan
Created June 19, 2024 17:34
Show Gist options
  • Save mikdusan/9a0ba0420eceb17a1220e37ed9606950 to your computer and use it in GitHub Desktop.
Save mikdusan/9a0ba0420eceb17a1220e37ed9606950 to your computer and use it in GitHub Desktop.
unix datagram server uds.c and client udc.c
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
int main() {
int fd = socket(PF_UNIX, SOCK_STREAM, 0);
if (fd == -1) {
perror("socket");
return -1;
}
struct sockaddr_un addr;
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, "jobs");
fprintf(stderr, "connect\n");
if (connect(fd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
perror("connect");
return -1;
}
fprintf(stderr, "write\n");
ssize_t rv = write(fd, "hello\n", 6);
if (rv == -1) {
perror("write");
return -1;
}
fprintf(stderr, "bytes: %ld\n", rv);
// fprintf(stderr, "sleep\n");
// sleep(10);
fprintf(stderr, "close\n");
close(fd);
}
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
int main() {
int fd = socket(PF_UNIX, SOCK_STREAM, 0);
if (fd == -1) {
perror("socket");
return -1;
}
struct sockaddr_un addr;
memset(&addr, 0, sizeof(addr));
addr.sun_family = AF_UNIX;
strcpy(addr.sun_path, "jobs");
fprintf(stderr, "bind\n");
if (bind(fd, (struct sockaddr *)&addr, sizeof(addr)) == -1) {
perror("bind");
return -1;
}
fprintf(stderr, "listen\n");
if (listen(fd, 5) == -1) {
perror("accept");
return -1;
}
fprintf(stderr, "accept\n");
struct sockaddr_un remote;
socklen_t len;
int client = accept(fd, (struct sockaddr *)&remote, &len);
if (client == -1) {
perror("accept");
return -1;
}
fprintf(stderr, "read\n");
char buf[1024];
ssize_t rv = read(client, buf, sizeof(buf));
if (rv == -1) {
perror("read");
return -1;
}
fprintf(stderr, "bytes: %ld\n", rv);
fprintf(stderr, "sleep\n");
sleep(60);
fprintf(stderr, "close\n");
close(fd);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment