Skip to content

Instantly share code, notes, and snippets.

@mikroskeem
Created March 28, 2015 11:36
Show Gist options
  • Save mikroskeem/38f07eb02e6cdb831c0c to your computer and use it in GitHub Desktop.
Save mikroskeem/38f07eb02e6cdb831c0c to your computer and use it in GitHub Desktop.
stdio to unix socket
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#define SOCK_PATH "echo_socket"
#define nop() asm volatile("nop")
int main(void){
int s, s2, t, len;
struct sockaddr_un local, remote;
pid_t child_pid;
char str[100];
if ((s = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
perror("socket");
exit(1);
}
local.sun_family = AF_UNIX;
strcpy(local.sun_path, SOCK_PATH);
unlink(local.sun_path);
len = strlen(local.sun_path) + sizeof(local.sun_family);
if (bind(s, (struct sockaddr *)&local, len) == -1) {
perror("bind");
exit(1);
}
if (listen(s, 5) == -1) {
perror("listen");
exit(1);
}
for(;;) {
int status, n;
printf("Waiting for a connection...\n");
t = sizeof(remote);
if ((s2 = accept(s, (struct sockaddr *)&remote, &t)) == -1) {
perror("accept");
exit(1);
}
printf("Connected\n");
child_pid = fork();
if(child_pid < 0){
perror("fork failed");
exit(1);
} else if(child_pid == 0){
if(handle(s2) < 0){
perror("something failed in child process");
_exit(1);
}
_exit(0);
} else {
while(wait(&status) != child_pid) nop();
close(s2);
}
}
return 0;
}
int handle(int s){
/* Close stdio */
close(0);
close(1);
close(2);
if(dup(s) != 0 || dup(s) != 1 || dup(s) != 2 ) {
return -1;
}
char *argv[] = {"/bin/bash", "/home/mark/coding/stdio-to-unix-socket/test.sh", 0};
char *env[] = {"PATH=/bin:/usr/bin", 0};
if (execve(*argv, argv, env) < 0) {
return -1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment