Files
mercury/compiler/process_util.m
Zoltan Somogyi 4ebe3d0d7e Stop storing globals in the I/O state, and divide mercury_compile.m
Estimated hours taken: 60
Branches: main

Stop storing globals in the I/O state, and divide mercury_compile.m
into smaller, more cohesive modules. (This diff started out as doing
only the latter, but it became clear that this was effectively impossible
without the former, and the former ended up accounting for the bulk of the
changes.)

Taking the globals out of the I/O state required figuring out how globals
data flowed between pieces of code that were often widely separated.
Such flows were invisible when globals could be hidden in the I/O state,
but now they are visible, because the affected code now passes around
globals structures explicitly.

In some cases, the old flow looked buggy, as when one job invoked by
mmc --make could affect the globals value of its parent or the globals value
passed to the next job. I tried to fix such problems when I saw them. I am
not 100% sure I succeeded in every case (I may have replaced old bugs with
new ones), but at least now the flow is out in the open, and any bugs
should be much easier to track down and fix.

In most cases, changes the globals after the initial setup are intended to be
in effect only during the invocation of a few calls. This used to be done
by remembering the initial values of the to-be-changed options, changing their
values in the globals in the I/O state, making the calls, and restoring the old
values of the options. We now simply create a new version of the globals
structure, pass it to the calls to be affected, and then discard it.

In two cases, when discovering reasons why (1) smart recompilation should
not be done or (2) item version numbers should not be generated, the record
of the discovery needs to survive this discarding. This is why in those cases,
we record the discovery by setting a mutable attached to the I/O state.
We use pure code (with I/O states) both to read and to write the mutables,
so this is no worse semantically than storing the information in the globals
structure inside the I/O state. (Also, we were already using such a mutable
for recording whether -E could add more information.)

In many modules, the globals information had to be threaded through
several predicates in the module. In some places, this was made more
difficult by predicates being defined by many clauses. In those cases,
this diff converts those predicates to using explicit disjunctions.

compiler/globals.m:
	Stop storing the globals structure in the I/O state, and remove
	the predicates that accessed it there.

	Move a mutable and its access predicate here from handle_options.m,
	since here is when the mutables treated the same way are.

	In a couple of cases, the value of an option is available in a mutable
	for speed of access from inside performance-critical code. Set the
	values of those mutables from the option when the processing of option
	values is finished, not when it is starting, since otherwise the copies
	of each option could end up inconsistent.

	Validate the reuse strategy option here, since doing it during ctgc
	analysis (a) is too late, and (b) would require an update to the
	globals to be done at an otherwise inconvenient place in the code.
	Put the reuse strategy into the globals structure.

	Two fields in the globals structure were unused. One
	(have_printed_usage) was made redundant when the one predicate
	that used it itself became unused; the other (source_file_map)
	was effectively replaced by a mutable some time ago. Delete
	these fields from the globals.

	Give the fields of the globals structure a distinguishing prefix.

	Put the type declarations, predicate declarations and predicate
	definitions in a consistent order.

compiler/source_file_map.m:
	Record this module's results only in the mutable (it serves as a
	cache), not in globals structure. Use explicitly passed globals
	structure for other purposes.

compiler/handle_options.m:
	Rename handle_options as handle_given_options, since it does not
	process THE options to the program, but the options it is given,
	and even during the processing of a single module, it can be invoked
	up the three times in a row, each time being given different options.
	(It was up to four times in a row before this diff.)

	Make handle_given_options explicitly return the globals structure it
	creates. Since it does not take an old global structure as input
	and globals are not stored in the I/O state, it is now clear that
	the globals structure it returns is affected only by the default values
	of the options and the options it processes. Before this diff,
	in the presence of errors in the options, handle_options *could*
	return (implicitly, in the I/O state) the globals structure that
	happened to be in the I/O state when it was invoked.

	Provide a separate predicate for generating a dummy globals based only
	on the default values of options. This allows by mercury_compile.m
	to stop abusing a more general-purpose predicate from handle_options.m,
	which we no longer export.

	Remove the mutable and access predicate moved to globals.m.

compiler/options.m:
	Document the fact that two options, smart_recompilation and
	generate_item_version_numbers, should not be used without seeing
	whether the functionalities they call for have been disabled.

compiler/mercury_compile_front_end.m:
compiler/mercury_compile_middle_passes.m:
compiler/mercury_compile_llds_back_end.m:
compiler/mercury_compile_mlds_back_end.m:
compiler/mercury_compile_erl_back_end.m:
	New modules carved out of the old mercury_compile.m. They each cover
	exactly the areas suggested by their names.

	Each of the modules is more cohesive than the old mercury_compile.m.
	Their code is also arranged in a more logical order, with predicates
	representing compiler passes being defined in the order of their
	invocation.

	Some of these modules export predicates for use by their siblings,
	showing the dependencies between the groups of passes.

compiler/top_level.m:
compiler/notes/compiler_design.html:
	Add the new modules.

compiler/mark_static_terms.m:
	Move this module from the ml_backend package to the hlds package,
	since (a) it does not depend on the MLDS in any way, and (b) it is
	also needed by a compiler pass (loop invariants) in the middle passes.

compiler/hlds.m:
compiler/ml_backend.m:
compiler/notes/compiler_design.html:
	Reflect mark_static_terms.m's change of package.

compiler/passes_aux.m:
	Move the predicates for dumping out the hLDS here from
	mercury_compile.m, since the new modules also need them.

	Look up globals in the HLDS, not the I/O state.

compiler/hlds_module.m:
	Store the prefix (common part) of HLDS dump file names in the HLDS
	itself, so that the code moved to passes_aux.m can figure out the
	file name for a HLDS dump without doing system calls.

	Give the field names of some structures prefixes to avoid ambiguity.

compiler/mercury_compile.m:
	Remove the code moved to the other modules. This module now looks
	after only option handling (such as deciding whether to generate .int3
	files, .int files, .opt files etc), and the compilation passes
	up to and including the creation of the first version of the HLDS.
	Everything after that is subcontracted to the new modules.

	Simplify and make explicit the flow of globals information.
	When invoking predicates that could disable smart recompilation,
	check whether they have done so, and if yes, update the globals
	accordingly.

	When compiling via gcc, we need to link into the executable
	the object files of any separate C files we generate for C code
	foreign_procs, which we cannot translate into gcc's internal
	structures without becoming a C compiler as well as a Mercury compiler.
	Instead of adding such files to the accumulating option for extra
	object files in the globals structure, we return their names using
	the already existing mechanism we have always used to link the object
	files of fact tables into the executable.

	Give several predicates more descriptive names. Put predicates
	in a more logical order.

compiler/make.m:
compiler/make.dependencies.m:
compiler/make.module_target.m:
compiler/make.module_dep_file.m:
compiler/make.program_target.m:
compiler/make.util.m:
	Require callers to supply globals structures explicitly, not via the
	I/O state. Afterward pass them around explicitly, passing modified
	versions to mercury_compile.m when invoking it with module- and/or
	task-specific options.

	Due the extensive use of partial application for higher order code
	in these modules, passing around the globals structures explicitly
	is quite tricky here. There may be cases where a predicate uses
	an old globals structure it got from a closure instead of the updated
	module- and/or task-specific globals it should be using, or vice versa.
	However, it is just as likely that, this diff fixes old problems
	by preventing the implicit flow of updated-only-for-one-invocation
	globals structures back to the original invoking context.

	Although I have tried to be careful about this, it is also possible
	that in some places, the code is using an updated-for-an-invocation
	globals structure in some but not all of the places where it
	SHOULD be used.

compiler/c_util.m:
compiler/compile_target_code.m:
compiler/compiler_util.m:
compiler/error_util.m:
compiler/file_names.m:
compiler/file_util.m:
compiler/ilasm.m:
compiler/ml_optimize.m:
compiler/mlds_to_managed.m:
compiler/module_cmds.m:
compiler/modules.m:
compiler/options_file.m:
compiler/pd_debug.m:
compiler/prog_io.m:
compiler/transform_llds.m:
compiler/write_deps_file.m:
	Require callers to supply globals structures explicitly, not via the
	I/O state.

	In some cases, the explicit globals structure argument allows
	a predicate to dispense with the I/O states previously passed to it.

	In some modules, rename some predicates, types and/or function symbols
	to avoid ambiguity.

compiler/read_modules.m:
	Require callers to supply globals structures explicitly, not via the
	I/O state.

	Record when smart recompilation and the generation of item version
	numbers should be disabled.

compiler/opt_debug.m:
compiler/process_util.m:
	Require callers to supply the needed options explicitly, not via the
	globals in the I/O state.

compiler/analysis.m:
compiler/analysis.file.m:
compiler/mmc_analysis.m:
	Make the analysis framework's methods take their global structures
	as explicit arguments, not as implicit data stored in the I/O state.

	Stop using `with_type` and `with_inst` declarations unnecessarily.

	Rename some predicates to avoid ambiguity.

compiler/hlds_out.m:
compiler/llds_out.m:
compiler/mercury_to_mercury.m:
compiler/mlds_to_c.m:
compiler/mlds_to_java.m:
compiler/optimize.m:
	Make these modules stop accessing the globals from the I/O state.
	Do this by requiring the callers of their top predicates to explicitly
	supply a globals structure. To compensate for the cost of having to
	pass around a representation of the options, look up the values of the
	options of interest just once, to make further access much faster.

	(In the case of mlds_to_c.m, the code already did much of this,
	but it still had a few accesses to globals in the I/O state that
	this diff eliminates.)

	If the module exports a predicate that needs these pre-looked-up
	options, then export the type of this data structure and its
	initialization function.

compiler/frameopt.m:
	Since this module needs only one option from the globals, pass that
	option instead of the globals.

compiler/accumulator.m:
compiler/add_clause.m:
compiler/closure_analysis.m:
compiler/complexity.m:
compiler/deforest.m:
compiler/delay_construct.m:
compiler/elds_to_erlang.m:
compiler/exception_analysis.m:
compiler/fact_table.m:
compiler/intermod.m:
compiler/mode_constraints.m:
compiler/mode_errors.m:
compiler/pd_util.m:
compiler/post_term_analysis.m:
compiler/recompilation.usage.m:
compiler/size_prof.usage.m:
compiler/structure_reuse.analysis.m:
compiler/structure_reuse.direct.choose_reuse.m:
compiler/structure_reuse.direct.m:
compiler/structure_sharing.analysis.m:
compiler/tabling_analysis.m:
compiler/term_constr_errors.m:
compiler/term_constr_fixpoint.m:
compiler/term_constr_initial.m:
compiler/term_constr_main.m:
compiler/term_constr_util.m:
compiler/trailing_analysis.m:
compiler/trans_opt.m:
compiler/typecheck_info.m:
	Look up globals information from the HLDS, not the I/O state.

	Conform to the changes above.

compiler/gcc.m:
compiler/maybe_mlds_to_gcc.pp:
compiler/mlds_to_gcc.m:
	Look up globals information from the HLDS, not the I/O state.

	Conform to the changes above.

	Convert these modules to our current programming style.

compiler/termination.m:
	Look up globals information from the HLDS, not the I/O state.

	Conform to the changes above.

	Report some warnings with error_specs, instead of immediately
	printing them out.

compiler/export.m:
compiler/il_peephole.m:
compiler/layout_out.m:
compiler/rtti_out.m:
compiler/liveness.m:
compiler/make_hlds.m:
compiler/make_hlds_passes.m:
compiler/mlds_to_il.m:
compiler/mlds_to_ilasm.m:
compiler/recompilation.check.m:
compiler/stack_opt.m:
compiler/superhomogeneous.m:
compiler/tupling..m:
compiler/unneeded_code.m:
compiler/unused_args.m:
compiler/unused_import.m:
compiler/xml_documentation.m:
	Conform to the changes above.

compiler/equiv_type_hlds.m:
	Give the field names of a structure prefixes to avoid ambiguity.

	Stop using `with_type` and `with_inst` declarations unnecessarily.

compiler/loop_inv.m:
compiler/pd_info.m:
compiler/stack_layout.m:
	Give the field names of some structures prefixes to avoid ambiguity.

compiler/add_pragma.m:
	Add notes.

compiler/string.m:
NEWS:
	Add a det version of remove_suffix, for use by new code above.
2009-10-14 05:28:53 +00:00

524 lines
15 KiB
Mathematica

%-----------------------------------------------------------------------------%
% vim: ft=mercury ts=4 sw=4 et
%-----------------------------------------------------------------------------%
% Copyright (C) 2002-2007, 2009 The University of Melbourne.
% This file may only be copied under the terms of the GNU General
% Public License - see the file COPYING in the Mercury distribution.
%-----------------------------------------------------------------------------%
%
% File: process_util.m.
% Main author: stayl.
%
% Process and signal handling, mainly for use by make.m and its sub-modules.
%
%-----------------------------------------------------------------------------%
%-----------------------------------------------------------------------------%
:- module libs.process_util.
:- interface.
:- import_module bool.
:- import_module io.
:- import_module maybe.
%-----------------------------------------------------------------------------%
:- type build0(Info) == pred(bool, Info, Info, io, io).
:- inst build0 == (pred(out, in, out, di, uo) is det).
:- type post_signal_cleanup(Info) == pred(Info, Info, io, io).
:- inst post_signal_cleanup == (pred(in, out, di, uo) is det).
% build_with_check_for_interrupt(VeryVerbose, Build, Cleanup, Succeeded,
% !Info, !IO):
%
% Apply `Build' with signal handlers installed to check for signals
% which would normally kill the process. If a signal occurs call `Cleanup',
% then restore signal handlers to their defaults and reraise the signal
% to kill the current process. An action being performed in a child process
% by call_in_forked_process will be killed if a fatal signal (SIGINT,
% SIGTERM, SIGHUP or SIGQUIT) is received by the current process.
% An action being performed within the current process or by system()
% will run to completion, with the interrupt being taken immediately
% afterwards.
%
:- pred build_with_check_for_interrupt(bool::in, build0(Info)::in(build0),
post_signal_cleanup(Info)::in(post_signal_cleanup), bool::out,
Info::in, Info::out, io::di, io::uo) is det.
% raise_signal(Signal).
% Send `Signal' to the current process.
%
:- pred raise_signal(int::in, io::di, io::uo) is det.
% send_signal(Signal, Pid).
% Send `Signal' to `Pid'.
%
:- pred send_signal(int::in, pid::in, io::di, io::uo) is det.
:- func sigint = int.
%-----------------------------------------------------------------------------%
:- type io_pred == pred(bool, io, io).
:- inst io_pred == (pred(out, di, uo) is det).
:- type pid == int.
% Does fork() work on the current platform.
%
:- pred can_fork is semidet.
% call_in_forked_process(P, AltP, Succeeded):
%
% Execute `P' in a separate process.
%
% We prefer to use fork() rather than system() because
% that will avoid shell and Mercury runtime startup overhead.
% Interrupt handling will also work better (system() on Linux
% ignores SIGINT).
%
% If fork() is not supported on the current architecture,
% `AltP' will be called instead in the current process.
%
:- pred call_in_forked_process_with_backup(io_pred::in(io_pred),
io_pred::in(io_pred), bool::out, io::di, io::uo) is det.
% As above, but if fork() is not available, just call the
% predicate in the current process.
%
:- pred call_in_forked_process(io_pred::in(io_pred), bool::out,
io::di, io::uo) is det.
% start_in_forked_process(P, Succeeded, !IO)
%
% Start executing `P' in a child process. Returns immediately, i.e. does
% not wait for `P' to finish. This predicate should only be called if
% fork() is available.
%
% The child process's exit code will be 0 if `P' returns a success value of
% `yes', or 1 if the success value is `no'.
%
:- pred start_in_forked_process(io_pred::in(io_pred), maybe(pid)::out,
io::di, io::uo) is det.
% wait_pid(Pid, ExitCode, !IO)
%
% Block until the child process with process id Pid exited.
% Return the exit code of the child.
%
:- pred wait_pid(pid::in, io.res(io.system_result)::out, io::di, io::uo)
is det.
% wait_any(Pid, ExitCode, !IO)
%
% Block until a child process has exited. Return the process ID
% of the child and its exit code.
%
:- pred wait_any(pid::out, io.res(io.system_result)::out, io::di, io::uo)
is det.
%-----------------------------------------------------------------------------%
%-----------------------------------------------------------------------------%
:- implementation.
:- import_module libs.compiler_util.
:- import_module libs.globals.
:- import_module libs.options.
%-----------------------------------------------------------------------------%
build_with_check_for_interrupt(VeryVerbose, Build, Cleanup, Succeeded,
!Info, !IO) :-
setup_signal_handlers(MaybeSigIntHandler, !IO),
Build(Succeeded0, !Info, !IO),
restore_signal_handlers(MaybeSigIntHandler, !IO),
check_for_signal(Signalled, Signal, !IO),
( Signalled = 1 ->
Succeeded = no,
(
VeryVerbose = yes,
io.write_string("** Received signal ", !IO),
io.write_int(Signal, !IO),
io.write_string(", cleaning up.\n", !IO)
;
VeryVerbose = no
),
Cleanup(!Info, !IO),
% The signal handler has been restored to the default,
% so this should kill us.
raise_signal(Signal, !IO)
;
Succeeded = Succeeded0
).
:- type signal_action ---> signal_action.
:- pragma foreign_type("C", signal_action, "MR_signal_action").
:- pragma foreign_decl("C",
"
#ifdef MR_HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef MR_HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef MR_HAVE_SYS_WAIT_H
#include <sys/wait.h>
#endif
#include <errno.h>
#include ""mercury_signal.h""
#include ""mercury_types.h""
#include ""mercury_heap.h""
#include ""mercury_misc.h""
#if defined(MR_HAVE_FORK) && defined(MR_HAVE_WAIT) && defined(MR_HAVE_KILL)
#define MC_CAN_FORK 1
#endif
#define MC_SETUP_SIGNAL_HANDLER(sig, handler) \
MR_setup_signal(sig, (MR_Code *) handler, MR_FALSE, \
""mercury_compile: cannot install signal handler"");
/* Have we received a signal. */
extern volatile sig_atomic_t MC_signalled;
/*
** Which signal did we receive.
** XXX This assumes a signal number will fit into a sig_atomic_t.
*/
extern volatile sig_atomic_t MC_signal_received;
void MC_mercury_compile_signal_handler(int sig);
").
:- pragma foreign_code("C",
"
volatile sig_atomic_t MC_signalled = MR_FALSE;
volatile sig_atomic_t MC_signal_received = 0;
void
MC_mercury_compile_signal_handler(int sig)
{
MC_signalled = MR_TRUE;
MC_signal_received = sig;
}
").
:- pred setup_signal_handlers(signal_action::out, io::di, io::uo) is det.
setup_signal_handlers(signal_action::out, IO::di, IO::uo).
:- pragma foreign_proc("C",
setup_signal_handlers(SigintHandler::out, IO0::di, IO::uo),
[will_not_call_mercury, promise_pure, tabled_for_io],
"{
IO = IO0;
MC_signalled = MR_FALSE;
/*
** mdb sets up a SIGINT handler, so we should restore
** it after we're done.
*/
MR_get_signal_action(SIGINT, &SigintHandler,
""error getting SIGINT handler"");
MC_SETUP_SIGNAL_HANDLER(SIGINT, MC_mercury_compile_signal_handler);
MC_SETUP_SIGNAL_HANDLER(SIGTERM, MC_mercury_compile_signal_handler);
#ifdef SIGHUP
MC_SETUP_SIGNAL_HANDLER(SIGHUP, MC_mercury_compile_signal_handler);
#endif
#ifdef SIGQUIT
MC_SETUP_SIGNAL_HANDLER(SIGQUIT, MC_mercury_compile_signal_handler);
#endif
}").
:- pred restore_signal_handlers(signal_action::in, io::di, io::uo) is det.
restore_signal_handlers(_::in, IO::di, IO::uo).
:- pragma foreign_proc("C",
restore_signal_handlers(SigintHandler::in, IO0::di, IO::uo),
[will_not_call_mercury, promise_pure, tabled_for_io],
"{
IO = IO0;
MR_set_signal_action(SIGINT, &SigintHandler,
""error resetting SIGINT handler"");
MC_SETUP_SIGNAL_HANDLER(SIGTERM, SIG_DFL);
#ifdef SIGHUP
MC_SETUP_SIGNAL_HANDLER(SIGHUP, SIG_DFL);
#endif
#ifdef SIGQUIT
MC_SETUP_SIGNAL_HANDLER(SIGQUIT, SIG_DFL);
#endif
}").
% Restore all signal handlers to default values in the child so that
% the child will be killed by the signals the parent is catching.
%
:- pred setup_child_signal_handlers(io::di, io::uo) is det.
setup_child_signal_handlers(!IO) :-
restore_signal_handlers(sig_dfl, !IO).
:- func sig_dfl = signal_action.
sig_dfl = (signal_action::out).
:- pragma foreign_proc("C",
sig_dfl = (Result::out),
[will_not_call_mercury, promise_pure],
"
MR_init_signal_action(&Result, SIG_DFL, MR_FALSE, MR_TRUE);
").
:- pred check_for_signal(int::out, int::out, io::di, io::uo) is det.
check_for_signal(0::out, 0::out, IO::di, IO::uo).
:- pragma foreign_proc("C",
check_for_signal(Signalled::out, Signal::out, IO0::di, IO::uo),
[will_not_call_mercury, promise_pure, tabled_for_io],
"
IO = IO0;
Signalled = (MC_signalled ? 1 : 0);
Signal = MC_signal_received;
").
%-----------------------------------------------------------------------------%
:- pragma foreign_decl("C", "#include <signal.h>").
% If this aborted it would cause partially built files
% to be left lying around with `--make'.
raise_signal(_::in, IO::di, IO::uo).
:- pragma foreign_proc("C",
raise_signal(Signal::in, IO0::di, IO::uo),
[will_not_call_mercury, promise_pure, tabled_for_io],
"
IO = IO0;
raise(Signal);
").
:- pragma foreign_proc("C",
send_signal(Pid::in, Signal::in, IO0::di, IO::uo),
[will_not_call_mercury, promise_pure, tabled_for_io],
"
IO = IO0;
#ifdef MR_HAVE_KILL
kill(Pid, Signal);
#endif
").
:- pragma foreign_proc("C",
sigint = (Sigint::out),
[will_not_call_mercury, promise_pure, thread_safe],
"
Sigint = SIGINT;
").
%-----------------------------------------------------------------------------%
call_in_forked_process(P, Success, !IO) :-
call_in_forked_process_with_backup(P, P, Success, !IO).
call_in_forked_process_with_backup(P, AltP, Success, !IO) :-
( can_fork ->
start_in_forked_process(P, MaybePid, !IO),
(
MaybePid = yes(Pid),
do_wait(Pid, _, CallStatus, !IO),
Status = io.handle_system_command_exit_status(CallStatus),
Success = (Status = ok(exited(0)) -> yes ; no)
;
MaybePid = no,
Success = no
)
;
AltP(Success, !IO)
).
can_fork :- semidet_fail.
:- pragma foreign_proc("C",
can_fork,
[will_not_call_mercury, thread_safe, promise_pure],
"
/*
** call_in_forked_process_2 is not `thread_safe' so will hold a mutex
** that the child process will want. At the same time the parent process
** waits for the child to exit, so we have a deadlock.
**
** Also, in pthreads, a forked process does not inherit the threads of
** the original process so it is not at all clear whether we could use
** fork() when running in a parallel grade.
*/
#if (defined MC_CAN_FORK) && (!defined MR_THREAD_SAFE)
SUCCESS_INDICATOR = MR_TRUE;
#else
SUCCESS_INDICATOR = MR_FALSE;
#endif
").
start_in_forked_process(P, MaybePid, !IO) :-
start_in_forked_process_2(P, Pid, !IO),
( Pid = 0 ->
MaybePid = no
;
MaybePid = yes(Pid)
).
:- pred start_in_forked_process_2(io_pred::in(io_pred), pid::out,
io::di, io::uo) is det.
start_in_forked_process_2(_, _, !IO) :-
sorry(this_file, "start_in_forked_process_2").
:- pragma foreign_proc("C",
start_in_forked_process_2(Pred::in(io_pred), Pid::out,
IO0::di, IO::uo),
[may_call_mercury, promise_pure, tabled_for_io],
"
#ifdef MC_CAN_FORK
IO = IO0;
Pid = fork();
if (Pid == -1) { /* error */
MR_perror(""error in fork()"");
} else if (Pid == 0) { /* child */
MR_Integer exit_status;
MC_call_child_process_io_pred(Pred, &exit_status);
exit(exit_status);
} else { /* parent */
}
#else /* ! MC_CAN_FORK */
IO = IO0;
Pid = 0;
#endif /* ! MC_CAN_FORK */
").
% call_child_process_io_pred(P, ExitStatus).
%
:- pred call_child_process_io_pred(io_pred::in(io_pred), int::out,
io::di, io::uo) is det.
:- pragma foreign_export("C",
call_child_process_io_pred(in(io_pred), out, di, uo),
"MC_call_child_process_io_pred").
call_child_process_io_pred(P, Status, !IO) :-
setup_child_signal_handlers(!IO),
P(Success, !IO),
(
Success = yes,
Status = 0
;
Success = no,
Status = 1
).
% do_wait(Pid, WaitedPid, Status, !IO)
%
% Wait until Pid exits and return its status.
% If Pid is -1 then wait for any child process to exit.
%
:- pred do_wait(pid::in, pid::out, int::out, io::di, io::uo) is det.
:- pragma foreign_proc("C",
do_wait(Pid::in, WaitedPid::out, Status::out, IO0::di, IO::uo),
[will_not_call_mercury, promise_pure, tabled_for_io],
"
#ifdef MC_CAN_FORK
{
int child_status;
pid_t wait_status;
/*
** Make sure the wait() is interrupted by the signals
** which cause us to exit.
*/
MR_signal_should_restart(SIGINT, MR_FALSE);
MR_signal_should_restart(SIGTERM, MR_FALSE);
#ifdef SIGHUP
MR_signal_should_restart(SIGHUP, MR_FALSE);
#endif
#ifdef SIGQUIT
MR_signal_should_restart(SIGQUIT, MR_FALSE);
#endif
while (1) {
wait_status = waitpid(Pid, &child_status, 0);
if (wait_status != -1) {
WaitedPid = wait_status;
Status = child_status;
break;
} else if (MR_is_eintr(errno)) {
if (MC_signalled) {
/*
** A normally fatal signal has been received, so kill the
** child immediately. Use SIGTERM, not MC_signal_received,
** because the child may be inside a call to system() which
** would cause SIGINT to be ignored on some systems (e.g.
** Linux).
*/
if (Pid != -1) {
kill(Pid, SIGTERM);
}
break;
}
} else {
/*
** This should never happen.
*/
MR_perror(""error in wait(): "");
Status = 1;
break;
}
}
/*
** Restore the system call signal behaviour.
*/
MR_signal_should_restart(SIGINT, MR_TRUE);
MR_signal_should_restart(SIGTERM, MR_TRUE);
#ifdef SIGHUP
MR_signal_should_restart(SIGHUP, MR_TRUE);
#endif
#ifdef SIGQUIT
MR_signal_should_restart(SIGQUIT, MR_TRUE);
#endif
}
#else /* ! MC_CAN_FORK */
MR_perror(""cannot wait() when fork() is unavailable: "");
IO = IO0;
Status = 1;
#endif /* ! MC_CAN_FORK */
").
wait_pid(Pid, Status, !IO) :-
do_wait(Pid, _Pid, Status0, !IO),
Status = io.handle_system_command_exit_status(Status0).
wait_any(Pid, Status, !IO) :-
do_wait(-1, Pid, Status0, !IO),
Status = io.handle_system_command_exit_status(Status0).
%-----------------------------------------------------------------------------%
:- func this_file = string.
this_file = "process_util.m".
%-----------------------------------------------------------------------------%
:- end_module libs.process_util.
%-----------------------------------------------------------------------------%