Skip to content

Instantly share code, notes, and snippets.

@cwgem cwgem/echo.c

Last active Aug 29, 2015
What would you like to do?
C Echo Server (utilizing linux namespaces)
/*Required Headers*/
#define _GNU_SOURCE
#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sched.h>
#include <stdlib.h>
#include <sys/wait.h>
#define STACK_SIZE 1024*1024*5
void sig_handler(int signo)
if (signo == SIGINT)
int echo_server()
printf("Child: PID=%ld PPID=%ld\n", (long) getpid(), (long) getppid());
char str[100];
int listen_fd, comm_fd;
struct sockaddr_in servaddr;
listen_fd = socket(AF_INET, SOCK_STREAM, 0);
bzero( &servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htons(INADDR_ANY);
servaddr.sin_port = htons(7);
bind(listen_fd, (struct sockaddr *) &servaddr, sizeof(servaddr));
signal(SIGINT, sig_handler);
listen(listen_fd, 10);
comm_fd = accept(listen_fd, (struct sockaddr*) NULL, NULL);
bzero( str, 100);
printf("Echoing back - %s",str);
write(comm_fd, str, strlen(str)+1);
return 0;
int main() {
char *stack;
char *stackTop;
stack = malloc(STACK_SIZE);
if (stack == NULL) {
printf("malloc(2) failed\n");
return 1;
stackTop = stack + STACK_SIZE;
pid_t child_pid = clone(echo_server, stackTop, CLONE_NEWPID | SIGCHLD, NULL);
waitpid(child_pid, NULL, 0);
return 0;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.