#include #include #include #include #include #include #include #include "piper_webext.h" static int pipe_out_fd; static void (*pipe_in_callback)(char *msg); // returns full path to pipe in users runtime dir. // dont forge't to g_free after use static gchar* getpath(char *path) { return g_strdup_printf("%s/piper-%s",g_get_user_runtime_dir(),path); } // callback function wrapper for received messages static gboolean mycallback(GIOChannel *ch, GIOCondition c, gpointer p) { gchar *line; g_io_channel_read_line(ch, &line, NULL, NULL, NULL); g_strchomp(line); pipe_in_callback(line); g_free(line); return true; } static void register_callback(char *path) { gchar *fullpath=getpath(path); mkfifo(fullpath,0600); GMainContext *ctx = g_main_context_default(); GIOChannel *io = g_io_channel_new_file(fullpath, "r+", NULL); GSource *watch = g_io_create_watch(io, G_IO_IN); g_source_attach(watch,ctx); g_source_set_callback(watch,(GSourceFunc)mycallback,NULL,NULL); g_free(fullpath); } // open for writing, lock and return pipe fd static int piper_lock(char *path) { gchar *fullpath=getpath(path); mkfifo(fullpath,0600); int pipe=open(fullpath, O_RDWR | O_CREAT | O_TRUNC); g_free(fullpath); if(pipe == -1) return -1; int lock=lockf(pipe,F_TLOCK,0); if(lock == -1) return -1; return pipe; } void piper_init(char *path_in,char *path_out,void (*callback_func)(char *msg)) { pipe_in_callback=callback_func; pipe_out_fd=piper_lock(path_out); if(pipe_out_fd==-1) { g_print("can not get exclusive lock! Bailing out.\n"); exit(0); } register_callback(path_in); } void piper_send(char *msg) { int ret=write(pipe_out_fd,msg,strlen(msg)); if(ret==-1)g_print("Can not write to pipe :(\n"); }