Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect to Unix domain socket as client in Haskel

I can't find a good info on dealing with Unix Domain sockets in Haskell. I need a simple function to open a socket and write a command to it. Can anyone help me with an advice of where to read about this or maybe give an example?

Basically, I need to port this simple Ruby function (if it helps to understand what I mean):

def monitor(string_command)
  require "socket"
  socket = File.join($vbase, @name, "monitor.soc")
  raise RuntimeError, "Monitor socket does not exst!" unless File.exist? socket
  begin
    UNIXSocket.open(socket) do |s|
      s.puts string_command
      s.flush
    end
  rescue
    return false
  end
  true
end

All it does opens socket and writes a command to it returning true upon success. Thank you.

like image 549
r.sendecky Avatar asked Feb 22 '12 02:02

r.sendecky


2 Answers

I think I figured it out. Well, it works and does what I need so I guess it should do for now.

Here is the snippet (without any error checks) if some one needs a similar thing:

monitor n c = do
  soc <- socket AF_UNIX Stream 0
  connect soc (SockAddrUnix (vmBaseDir </> n </> "monitor.soc"))
  send soc (c ++ "\n")
  sClose soc
like image 93
r.sendecky Avatar answered Nov 07 '22 08:11

r.sendecky


Here is a full example:

{-# Language OverloadedStrings #-}
module Main where

import Network.Socket hiding (send)
import Network.Socket.ByteString

main :: IO ()
main = do
  withSocketsDo $ do
    soc <- socket AF_UNIX Stream 0
    connect (soc) (SockAddrUnix "/tmp2/test2.soc")
    send soc ("test123")
    close soc
like image 39
Chris Stryczynski Avatar answered Nov 07 '22 08:11

Chris Stryczynski