How can I exit my Dart (vm) program? - exit

(Sorry, I know that is this is mostly a repeat of John Evan's question, but the previous answer must now be outdated.)
I'd like to be able to specify an exitCode and leave the my (vm) program if a certain condition occurs (for debugging purposes only).
Note from the above I cannot import 'dart:builtin', and I can't find mention of exit() in this context in the API.
(My more detailed situation is that my work involves rather massive detailed output and as I test and debug things I have found it most convenient to just exit(); the program - clearly only appropriate during development.)
Thanks,
_g

Just use exit():
import 'dart:io';
void main() {
exit(0); // Standard out code, 0 = no errors.
}

Further searching has shown that the required support is now in the 'io' library so this is working for me:
(Nothing specific to an error code is getting printed out at the console, but that's ok.)
import('dart:io');
main() {
print("just before the exit command...");
exit(99);
print("We should not see this")
}

Related

Why storage fault in regex destructor?

I am getting a storage fault when my code destructs a regex and I am mystified as to the reason. I suspect I am missing something stupid about regex.
A little background: I am a reasonably experienced C++ developer but this is my first adventure with the regex class. My environment is a little unusual: I edit and alpha test in MS Visual C++ and then take the code to another environment. The other environment is fully Posix-compliant and just happens to be an IBM mainframe. The code works fine on Windows but fails every time on the mainframe. The problem is not something fundamental to my mixed environment: I have been working in this pair of environments in this way for years with complete C++ success.
I define the regex in the class declaration:
#include <regex>
...
class FilterEvalEGNX : public FilterEval
{
...
std::tr1::basic_regex<char> regexObject;
// I also tried plain regex with no difference
Subsequently in the class implementation I assign a pattern to the regex. The code should be more complex than this but I simplified it down to assigning a static string to eliminate any possible side effects from the way the string would be handled in real life.
std::tr1::regex::flag_type flags = std::tr1::regex::extended;
// I have also tried ECMA and it made no difference
try
{
static const char pat[] = "(ISPPROF|SPFTEMP)";
regexObject.assign(pat, flags);
}
catch (std::tr1::regex_error &e)
{
// handle regex error
}
That works without error. Of course, there is subsequent pattern matching code but it is not part of the problem: if I destruct the class immediately after the above code I get the storage fault.
I don't do anything to the regex in my class destructor. The rest of the class has been working for years; I am adding the regex now. I think some "external" overlay of the regex is unlikely.
Here is the traceback of the calls leading up to the fault:
std::tr1::_EBCDIC::_Destroy(std::tr1::_EBCDIC::_Node_base*)
+00000066 40 CRTE128N Exception
std::tr1::_EBCDIC::basic_regex<char,std::tr1::_EBCDIC::regex
+000000C8 2022 FilterEvalEGNX.C Call
std::tr1::_EBCDIC::basic_regex<char,std::tr1::_EBCDIC::regex
+0000007C 1913 FilterEvalEGNX.C Call
FilterEvalEGNX::~FilterEvalEGNX()
The code in the vicinity of line 1913 of regex is
~basic_regex()
{ // destroy the object
_Tidy();
}
The code in the vicinity of line 2022 of regex is
void _Tidy()
{ // free all storage
if (_Rep && --_Rep->_Refs == 0)
_Destroy(_Rep);
_Rep = 0;
}
_Destroy() appears to be implemented in the run-time and I do not think I have the source.
Any ideas? Thanks,
Believe it or not, it appears to be a bug in the C++ runtime. I tweaked my simple example and now I can duplicate the problem in a 15-line main(). I am going to run this by some peers and then report it to IBM. They actually fix this stuff! They don't just respond with "yes, you have found an issue."

How to get list of files opened by a process in Windows? [duplicate]

How do I get the list of open file handles by process id in C#?
I'm interested in digging down and getting the file names as well.
Looking for the programmatic equivalent of what process explorer does.
Most likely this will require interop.
Considering adding a bounty on this, the implementation is nasty complicated.
Ouch this is going to be hard to do from managed code.
There is a sample on codeproject
Most of the stuff can be done in interop, but you need a driver to get the filename cause it lives in the kernel's address space. Process Explorer embeds the driver in its resources. Getting this all hooked up from C# and supporting 64bit as well as 32, is going to be a major headache.
You can also run the command line app, Handle, by Mark Rusinovich, and parse the output.
Have a look at this file :
http://vmccontroller.codeplex.com/SourceControl/changeset/view/47386#195318
And use:
DetectOpenFiles.GetOpenFilesEnumerator(processID);
Demo:
using System;
using System.Diagnostics;
namespace OpenFiles
{
class Program
{
static void Main(string[] args)
{
using (var openFiles = VmcController.Services.DetectOpenFiles.GetOpenFilesEnumerator(Process.GetCurrentProcess().Id))
{
while (openFiles.MoveNext())
{
Console.WriteLine(openFiles.Current);
}
}
Console.WriteLine();
Console.ReadKey();
}
}
}
It has dependency over assembly System.EnterpriseServices
You can P/INVOKE into the NtQuerySystemInformation function to query for all handles and then go from there. This Google groups discussion has details.
Take a look at wj32's Process Hacker version 1, which can do what you asked, and more.
Handle is great program, and the link to codeproject is good.
#Brian
The reason for the code is that handle.exe is NOT redistributable. Nor do they release their source.
It looks as if .Net will not easily do this since it appears that an embedded device drive is requried to access the information. This cannot be done in .net without an unmanged DLL. It's relatviely deep kernel code when compared to typical .net coding. I'm surprised that WMI does not expose this.
Perhaps using command line tool:
OpenedFilesView v1.50 - View opened/locked files in your system (sharing violation issues)
http://www.nirsoft.net/utils/opened_files_view.html

Monitor/Output emitted Qt-Signals

I defined some signals which are emitted on different occasions:
signals:
void buttonXClicked(int x);
void numButtonsChanged(int num);
Now I would just like to see how these signals look like and if the parameters are correct. It seems there are several approaches to monitor the signals.
In the post here rohanpm refers to the parameter -vs which is specified closer here:
http://qt-project.org/doc/qt-4.8/qtestlib-manual.html#qtestlib-command-line-arguments
This seems to be an elegant and quick way of getting the information I require.
But to be honest I'm unable to understand how and where I have to run -vs. It's not part of qmake. Where else do I have to put it? (I'm pretty new to qt).
Related to the QSignalSpy it seems to be necessary to change the existing classes? Isn't there an "external" approach as well?
There is plenty of documentation around how to test a slot - but related to signals? Could I use a printf or cout somewhere?
I got this idea while reading more about the moc and its functionality. (At least while using NetBeans) I get additional to my File ButtonTest.cpp the file moc_ButtonTest.cpp. Inside is a method called:
// SIGNAL 0
void ButtonTest::buttonXClicked(int _t1)
{
void *_a[] = { 0, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
I could hardly believe it was so easy but I've just added a
std::cout <<"buttonXClicked: "<<_t1;
and it seems to do exactly what I want.
As the linked documentation writes:
Runs the toUpper test function with all available test data, and the toInt test function with the testdata called zero (if the specified test data doesn't exist, the associated test will fail).
/myTestDirectory$ testMyWidget -vs -eventdelay 500
where testMyWidget is the test binary built. Here goes the -vs documentation:
-vs
outputs every signal that gets emitted
There is also some more documentation if you grep the help output:
/myTestDirectory$ testMyWidget --help | grep "\-vs"
-vs outputs every signal that gets emitted
If you happen to have trouble with writing QTestLib based unit tests, this is a good starting point for you with Qt 4:
QTestLib Manual

How to make a system call and read the stdout, in D?

I thought to try using D for some system administration scripts which require high performance (for comparing performance with python/perl etc).
I can't find an example in the tutorials I looked through so far (dsource.org etc.) on how to make a system call (i.e. calling another software) and receiving it's output from stdout, though?
If I missed it, could someone point me to the right docs/tutorial, or provide with the answer right away?
Well, then I of course found it: http://www.digitalmars.com/d/2.0/phobos/std_process.html#shell (Version using the Tango library here: http://www.dsource.org/projects/tango/wiki/TutExec).
The former version is the one that works with D 2.0 (thereby the current dmd compiler that comes with ubuntu).
I got this tiny example to work now, compiled with dmd:
import std.stdio;
import std.process;
void main() {
string output = shell("ls -l");
write(output);
}
std.process has been updated since... the new function is spawnShell
import std.stdio;
import std.process;
void main(){
auto pid = spawnShell("ls -l");
write(pid);
}

How to terminate a program when it crashes? (which should just fail a unit test instead of getting stuck forever)

Our unit tests fire off child processes, and sometimes these child processes crash. When this happens, a Windows Error Reporting dialog pops up, and the process stays alive until this is manually dismissed. This of course prevents the unit tests from ever terminating.
How can this be avoided?
Here's an example dialog in Win7 with the usual settings:
If I disable the AeDebug registry key, the JIT debugging option goes away:
If I disable checking for solutions (the only thing I seem to have control over via the control panel), it looks like this, but still appears and still stops the program from dying until the user presses something. WerAddExcludedApplication is documented to also have this effect.
A summary from the answers by jdehaan and Eric Brown, as well as this question (see also this question):
N.B. These solutions may affect other error reporting as well, e.g. failure to load a DLL or open a file.
Option 1: Disable globally
Works globally on the entire user account or machine, which can be both a benefit and a drawback.
Set [HKLM|HKCU]\Software\Microsoft\Windows\Windows Error Reporting\DontShowUI to 1.
More info: WER settings.
Option 2: Disable for the application
Requires modification to the crashing program, described in documentation as best practice, unsuitable for a library function.
Call SetErrorMode: SetErrorMode(SetErrorMode(0) | SEM_NOGPFAULTERRORBOX); (or with SEM_FAILCRITICALERRORS). More info: Disabling the program crash dialog (explains the odd arrangement of calls).
Option 2a: Disable for a function:
Requires modification to the crashing program, requires Windows 7/2008 R2 (desktop apps only) or higher, described in documenation as preferred to SetErrorMode, suitable for a thread-safe library function.
Call and reset SetThreadErrorMode:
DWORD OldThreadErrorMode = 0;
SetThreadErrorMode(SEM_FAILCRITICALERRORS,& OldThreadErrorMode);
…
SetThreadErrorMode (z_OldThreadErrorMode, NULL);
More info: not much available?
Option 3: Specify a handler
Requires modification to the crashing program.
Use SetUnhandledExceptionFilter to set your own structured exception handler that simply exits, probably with reporting and possibly an attempt at clean-up.
Option 4: Catch as an exception
Requires modification to the crashing program. For .NET applications only.
Wrap all code into a global try/catch block. Specify the HandleProcessCorruptedStateExceptionsAttribute and possibly also the SecurityCriticalAttribute on the method catching the exceptions. More info: Handling corrupted state exceptions
Note: this might not catch crashes caused by the Managed Debugging Assistants; if so, these also need to be disabled in the application.
Option 5: Stop the reporting process
Works globally on the entire user account, but only for a controlled duration.
Kill the Windows Error Reporting process whenever it shows up:
var werKiller = new Thread(() =>
{
while (true)
{
foreach (var proc in Process.GetProcessesByName("WerFault"))
proc.Kill();
Thread.Sleep(3000);
}
});
werKiller.IsBackground = true;
werKiller.Start();
This is still not completely bullet-proof though, because a console application may crash via a different error message, apparently displayed by an internal function called NtRaiseHardError:
The only solution is to catch all exceptions at a very high level (for each thread) and terminate the application properly (or perform another action).
This is the only way to prevent the exception from escaping your app and activating WER.
Addition:
If the exception is something you do not except to happen you can use an AssertNoThrow(NUnit) or alike in another Unit Test framework to enclose the code firing the child processes. This way you would also get it into your Unit test report. This is in my opinion the cleanest possible solution I can think of.
Addition2:
As the comments below show, I was mistaken: you cannot always catch the asynchronous exceptions, it depends on what the environment allows. In .NET some exceptions are prevented from being caught, what makes my idea worthless in this case...
For .NET: There are complicated workarounds involving the use of AppDomains, leading to an unload of an AppDomain instead of a crash of the whole application. Too bad...
http://www.bluebytesoftware.com/blog/PermaLink,guid,223970c3-e1cc-4b09-9d61-99e8c5fae470.aspx
http://www.develop.com/media/pdfs/developments_archive/AppDomains.pdf
EDIT:
I finally got it. With .NET 4.0 You can add the HandleProcessCorruptedStateExceptions attribute from System.Runtime.ExceptionServices to the method containing the try/catch block. This really worked! Maybe not recommended but works.
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.ExceptionServices;
namespace ExceptionCatching
{
public class Test
{
public void StackOverflow()
{
StackOverflow();
}
public void CustomException()
{
throw new Exception();
}
public unsafe void AccessViolation()
{
byte b = *(byte*)(8762765876);
}
}
class Program
{
[HandleProcessCorruptedStateExceptions]
static void Main(string[] args)
{
Test test = new Test();
try {
//test.StackOverflow();
test.AccessViolation();
//test.CustomException();
}
catch
{
Console.WriteLine("Caught.");
}
Console.WriteLine("End of program");
}
}
}
Try setting
HKCU\Software\Microsoft\Windows\Windows Error Reporting\DontShowUI
to 1. (You can also set the same key in HKLM, but you need admin privs to do that.)
This should prevent WER from showing any UI.