Skip to content

Instantly share code, notes, and snippets.

@ssrlive
Created March 28, 2024 05:44
Show Gist options
  • Save ssrlive/755a47b18cdb968d332f7461d6b20f4a to your computer and use it in GitHub Desktop.
Save ssrlive/755a47b18cdb968d332f7461d6b20f4a to your computer and use it in GitHub Desktop.
socketpair usage
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/socket.h>
void child(int sock) {
char buf[1024];
while (1) {
ssize_t n = read(sock, buf, sizeof(buf));
if (n <= 0) {
perror("read");
exit(1);
}
write(STDOUT_FILENO, buf, n);
}
}
void parent(int sock) {
char buf[1024];
while (1) {
ssize_t n = read(STDIN_FILENO, buf, sizeof(buf));
if (n <= 0) {
perror("read");
exit(1);
}
write(sock, buf, n);
}
}
int main(void) {
int sv[2];
if (socketpair(AF_UNIX, SOCK_STREAM, 0, sv) == -1) {
perror("socketpair");
exit(1);
}
pid_t pid = fork();
if (pid == -1) {
perror("fork");
exit(1);
} else if (pid == 0) {
close(sv[0]);
child(sv[1]);
} else {
close(sv[1]);
parent(sv[0]);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment