# Quit Mathematica script (no matter what)

I have a complicated script (not just written by me) that gets called using MathKernel -script script.m. Among others script.m uses parallel subkernels and external calls through RunProcess and OpenRead["!"<>cmd]. I sometimes encounter a situation where all lines until Quit get run yet the task never completes. So something of the form

lotsOfCode
...
Print["We arrived at Quit"];
Quit[]


Here "We arrived at Quit" will print but the task will never Quit. lotsOfCode should be viewed as a black box. What could be preventing the script from terminating? How can I really Quit?

System: Linux, Mathematica 11.1 (and 12.1)

I am happy with a linux based solution so I'm thinking I should probably invoke something like kill through something like RunProcess in order to get Mathematica to kill itself. A cleaner Mathematica based solution that figures out what is preventing it from quiting would of course be nicer.

This question seems related though it is looking for a different type of solution.

• A minimal example of code that has this problem would help. Jun 22, 2021 at 15:24
• @JohnDoty, I understand. If I can find one I will of course add it. Note that it is something that a.) Does not occur reliable, i.e. the same code can sometimes have this halting behaviour and other times not. b.) I find it in this big code and have not yet reproduced it in something compact. So for now I would appreciate it if the question could focus on what could possibly make Quit[] fail. Of course I understand that this makes the question more difficult to answer. In the linked question a minimal example with a function called sleepy is constructed. Perhaps that one can be kept in mind. Jun 22, 2021 at 15:28
• Quit should never be necessary in a script. Jun 22, 2021 at 15:31
• Taking Quit out gives the same hanging result. Quit is there to emphasize that the very last line just before it got reached and yet the script did not terminate. Jun 22, 2021 at 15:32
• @Szabolcs, I don't think it solves the issue as it actually initially occurred without any explicit Quit present but are you saying that Quit would not work? (As in act as Abort[] to finish the computation so that the script terminates.) Jun 22, 2021 at 15:40

It seems that replacing Quit[] with CloseKernels[]; Pause[5]; Quit[] solves the issue as pointed out in a comment to a related question.