]>
Commit | Line | Data |
---|---|---|
1 | package Gruntmaster::Daemon::Format; | |
2 | ||
3 | use 5.014000; | |
4 | use strict; | |
5 | use warnings; | |
6 | use parent qw/Exporter/; | |
7 | no if $] > 5.017011, warnings => 'experimental::smartmatch'; | |
8 | ||
9 | use POSIX qw//; | |
10 | use File::Basename qw/fileparse/; | |
11 | use Gruntmaster::Daemon::Constants qw/TLE OLE DIED NZX/; | |
12 | use Log::Log4perl qw/get_logger/; | |
13 | use Time::HiRes qw/alarm/; | |
14 | use List::MoreUtils qw/natatime/; | |
15 | use IPC::Signal qw/sig_name sig_num/; | |
16 | use IPC::Open3 qw/open3/; | |
17 | use File::Spec::Functions qw/devnull/; | |
18 | use Fcntl qw/F_GETFD F_SETFD FD_CLOEXEC/; | |
19 | ||
20 | our $VERSION = '0.001'; | |
21 | our @EXPORT_OK = qw/mkrun/; | |
22 | ||
23 | ################################################## | |
24 | ||
25 | sub command_and_args{ | |
26 | my ($format, $basename) = @_; | |
27 | ||
28 | given($format) { | |
29 | "./$basename" when [qw/C CPP PASCAL/]; | |
30 | "./$basename.exe" when 'MONO'; | |
31 | "java $basename" when 'JAVA'; | |
32 | "perl $basename" when 'PERL'; | |
33 | "python $basename" when 'PYTHON'; | |
34 | default { die "Don't know how to execute format $format" } | |
35 | } | |
36 | } | |
37 | ||
38 | sub mkrun{ | |
39 | my $format = shift; | |
40 | sub{ | |
41 | my ($name, %args) = @_; | |
42 | my $basename = fileparse $name, qr/\.[^.]*/; | |
43 | my $ret = fork // die 'Cannot fork'; | |
44 | if ($ret) { | |
45 | my $tle; | |
46 | local $SIG{ALRM} = sub { kill KILL => $ret; $tle = 1}; | |
47 | alarm $args{timeout} if exists $args{timeout}; | |
48 | wait; | |
49 | alarm 0; | |
50 | my $sig = $? & 127; | |
51 | my $signame = sig_name $sig; | |
52 | die [TLE, "Time Limit Exceeded"] if $tle; | |
53 | die [OLE, 'Output Limit Exceeded'] if $sig && $signame eq 'XFSZ'; | |
54 | die [DIED, "Crash (SIG$signame)"] if $sig; | |
55 | die [NZX, "Non-zero exit status: " . ($? >> 8)] if $?; | |
56 | } else { | |
57 | my @fds = exists $args{fds} ? @{$args{fds}} : (); | |
58 | $^F = 50; | |
59 | POSIX::close $_ for 0 .. $^F; | |
60 | my $it = natatime 2, @fds; | |
61 | while (my ($fd, $file) = $it->()) { | |
62 | open my $fh, $file or die $!; | |
63 | my $oldfd = fileno $fh; | |
64 | if ($oldfd != $fd) { | |
65 | POSIX::dup2 $oldfd, $fd or die $!; | |
66 | POSIX::close $oldfd or die $!; | |
67 | } | |
68 | } | |
69 | exec 'gruntmaster-exec', $args{mlimit} // 0, $args{olimit} // 0, command_and_args($format, $basename), exists $args{args} ? @{$args{args}} : (); | |
70 | exit 42 | |
71 | } | |
72 | } | |
73 | } | |
74 | ||
75 | 1 |