 		} else {
 			mTerminationStatus = 0
 		}
+		mThreadState = .Finished
+	}
+
+	public func waitUntilExit() {
+		while self.threadState != .Finished {
+			Thread.sleep(forTimeInterval: 1/10000.0) // 0.1ms
+		}
 	}
 }
 

		compiler.defineBuiltinFunctions(parentThread: self, context: mContext)
	}

	public override var terminationStatus: Int32 {
		get { return mTerminationStatus }
	}

	public func start(userScripts scripts: Array<URL>, arguments args: Array<String>) {
		mScripts   = scripts
		mArguments = args
		super.start()
	}

	public override func main() {
		guard let conf = config as? KHConfig else {
			NSLog("Can not happen")
			return
		}



@objc public class KHScriptThread: CNPipeThread, KHThreadProtocol
{
	public enum ThreadState {
		case Initial
		case Running
		case Finished
	}

	public static let EnvironmentItem	= "_env"

	private var mContext:			KEContext
	private var mScripts:			Array<URL>
	private var mArguments:			Array<String>
	private var mTerminationStatus:		Int32
	private var mThreadState:		ThreadState

	public init(virtualMachine vm: JSVirtualMachine, shellInterface intf: CNShellInterface, environment env: CNShellEnvironment, console cons: CNConsole, config conf: KHConfig){
		mContext		= KEContext(virtualMachine: vm)
		mScripts		= []
		mArguments		= []
		mTerminationStatus	= 1
		mThreadState		= .Initial
		super.init(interface: intf, environment: env, console: cons, config: conf)

		/* Compile the context */
