]> git.sur5r.net Git - i3/i3/blob - testcases/lib/StartXDummy.pm
testcases: move Xdummy cleanup code to StartXDummy
[i3/i3] / testcases / lib / StartXDummy.pm
1 package StartXDummy;
2 # vim:ts=4:sw=4:expandtab
3
4 use strict;
5 use warnings;
6 use Exporter 'import';
7 use Time::HiRes qw(sleep);
8 use v5.10;
9
10 our @EXPORT = qw(start_xdummy);
11
12 # reads in a whole file
13 sub slurp {
14     open(my $fh, '<', shift) or return '';
15     local $/;
16     <$fh>;
17 }
18
19 =head2 start_xdummy($parallel)
20
21 Starts C<$parallel> (or number of cores * 2 if undef) Xdummy processes (see
22 the file ./Xdummy) and returns two arrayrefs: a list of X11 display numbers to
23 the Xdummy processes and a list of PIDs of the processes.
24
25 =cut
26
27 my $x_socketpath = '/tmp/.X11-unix/X';
28
29 sub start_xdummy {
30     my ($parallel) = @_;
31
32     my @displays = ();
33     my @childpids = ();
34
35     # Yeah, I know it’s non-standard, but Perl’s POSIX module doesn’t have
36     # _SC_NPROCESSORS_CONF.
37     my $cpuinfo = slurp('/proc/cpuinfo');
38     my $num_cores = scalar grep { /model name/ } split("\n", $cpuinfo);
39     # If /proc/cpuinfo does not exist, we fall back to 2 cores.
40     $num_cores ||= 2;
41
42     $parallel ||= $num_cores * 2;
43
44     # First get the last used display number, then increment it by one.
45     # Effectively falls back to 1 if no X server is running.
46     my ($displaynum) = map { /(\d+)$/ } reverse sort glob($x_socketpath . '*');
47     $displaynum++;
48
49     say "Starting $parallel Xdummy instances, starting at :$displaynum...";
50
51     my @sockets_waiting;
52     for my $idx (0 .. ($parallel-1)) {
53         my $pid = fork();
54         die "Could not fork: $!" unless defined($pid);
55         if ($pid == 0) {
56             # Child, close stdout/stderr, then start Xdummy.
57             close STDOUT;
58             close STDERR;
59             # make sure this display isn’t in use yet
60             $displaynum++ while -e ($x_socketpath . $displaynum);
61
62             # We use -config /dev/null to prevent Xdummy from using the system
63             # Xorg configuration. The tests should be independant from the
64             # actual system X configuration.
65             exec './Xdummy', ":$displaynum", '-config', '/dev/null';
66             exit 1;
67         }
68         push(@main::CLEANUP, sub { kill(15, $pid) });
69         push(@displays, ":$displaynum");
70         push(@sockets_waiting, $x_socketpath . $displaynum);
71         $displaynum++;
72     }
73
74     # Wait until the X11 sockets actually appear. Pretty ugly solution, but as
75     # long as we can’t socket-activate X11…
76     while (1) {
77         @sockets_waiting = grep { ! -S $_ } @sockets_waiting;
78         last unless @sockets_waiting;
79         sleep 0.1;
80     }
81
82     return @displays;
83 }
84
85 1