1 package SocketActivation;
2 # vim:ts=4:sw=4:expandtab
4 use IO::Socket::UNIX; # core
5 use Cwd qw(abs_path); # core
7 use AnyEvent::Handle; # not core
11 our @EXPORT = qw(activate_i3);
14 # Starts i3 using socket activation. Creates a listening socket (with bind +
15 # listen) which is then passed to i3, who in turn calls accept and handles the
18 # Since the kernel buffers the connect, the parent process can connect to the
19 # socket immediately after forking. It then sends a request and waits until it
20 # gets an answer. Obviously, i3 has to be initialized to actually answer the
23 # This way, we can wait *precisely* the amount of time which i3 waits to get
24 # ready, which is a *HUGE* speed gain (and a lot more robust) in comparison to
25 # using sleep() with a fixed amount of time.
27 # unix_socket_path: Location of the socket to use for the activation
28 # display: X11 $ENV{DISPLAY}
29 # configfile: path to the configuration file to use
30 # logpath: path to the logfile to which i3 will append
31 # cv: an AnyEvent->condvar which will be triggered once i3 is ready
36 # remove the old unix socket
37 unlink($args{unix_socket_path});
39 # pass all file descriptors up to three to the children.
40 # we need to set this flag before opening the socket.
41 open(my $fdtest, '<', '/dev/null');
42 $^F = fileno($fdtest);
44 my $socket = IO::Socket::UNIX->new(
46 Local => $args{unix_socket_path},
51 die "could not fork()";
54 $ENV{LISTEN_PID} = $$;
56 $ENV{DISPLAY} = $args{display};
59 # If the socket does not use file descriptor 3 by chance already, we
60 # close fd 3 and dup2() the socket to 3.
61 if (fileno($socket) != 3) {
63 POSIX::dup2(fileno($socket), 3);
67 my $i3cmd = abs_path("../i3") . " -V -d all --disable-signalhandler";
68 my $cmd = "exec $i3cmd -c $args{configfile} >$args{logpath} 2>&1";
69 exec "/bin/sh", '-c', $cmd;
71 # if we are still here, i3 could not be found or exec failed. bail out.
75 # close the socket, the child process should be the only one which keeps a file
76 # descriptor on the listening socket.
79 # We now connect (will succeed immediately) and send a request afterwards.
80 # As soon as the reply is there, i3 is considered ready.
81 my $cl = IO::Socket::UNIX->new(Peer => $args{unix_socket_path});
83 $hdl = AnyEvent::Handle->new(
90 # send a get_tree message without payload
91 $hdl->push_write('i3-ipc' . pack("LL", 0, 4));
94 $hdl->push_read(chunk => 1, => sub {