usocket.c
author viric@llimona
Fri, 14 Sep 2007 23:47:40 +0200
changeset 15 0acf8c3c4fe0
parent 14 286b248e402a
permissions -rw-r--r--
Good routing of app's stderr.

/*
    stdin mix - a mixer/multiplexer for stdin to processes
    Copyright (C) 2007  LluĂ­s Batlle i Rossell

    Please find the license in the provided COPYING file.
*/
#include <stdlib.h>
#include <sys/un.h>
#include <sys/socket.h>

#include "main.h"

static char socket_path[256];
static char default_path_prefix[] = "/tmp/socket-sm.";

static void get_path()
{
    char *new;
    
    new = getenv("SM_SOCKET");
    if (new == 0)
    {
        char num[20];
        snprintf(socket_path, sizeof(socket_path), "%s%i",
                default_path_prefix, (int) getuid());
    } else
        strncpy(socket_path, new, sizeof(socket_path));
}

int serve_socket()
{
    int ls;
    struct sockaddr_un addr;
    int res;

    get_path();

    ls = socket(AF_UNIX, SOCK_STREAM, 0);
    if (ls == -1)
        error("Cannot create the unix listen socket in the server");

    addr.sun_family = AF_UNIX;
    strncpy(addr.sun_path, socket_path, sizeof(addr.sun_path));

    res = bind(ls, (struct sockaddr *) & addr, sizeof(addr));
    if (res == -1)
        error("Error binding to %s", socket_path);

    res = listen(ls, 10);
    if (res == -1)
        error("Error listening on the binded unix socket");

    return ls;
}

int accept_connection(int ls)
{
    int cs;
    cs = accept(ls, 0, 0);
    return cs;
}

int connect_socket()
{
    struct sockaddr_un addr;
    int res;
    int cs;

    get_path();

    cs = socket(AF_UNIX, SOCK_STREAM, 0);
    if (cs == -1)
        error("Cannot create the unix connect socket in the client");

    addr.sun_family = AF_UNIX;
    strncpy(addr.sun_path, socket_path, sizeof(addr.sun_path));

    res = connect(cs, (struct sockaddr *) &addr, sizeof(addr));
    if (res == -1)
        error("Cannot connect to %s", socket_path);
    return cs;
}

void remove_socket(int ls)
{
    close(ls);
    unlink(socket_path);
}