/// <summary> /// 数据压缩 /// </summary> /// <param name="s">待压缩数据输入流</param> /// <param name="os">压缩后的数据输出流</param> /// <param name="deflater">压缩器</param> public static void Compress(Stream s, Stream os, Deflater deflater) { DeflaterOutputStream dos = new DeflaterOutputStream(os, deflater, 1024 * 4); Stdio.CopyStream(s, dos); dos.Finish(); }
/// <summary> /// GZip解压 /// </summary> /// <param name="s">待解压数据输入流</param> /// <param name="os">解压后的数据输出流</param> public static void GZipDecompress(Stream s, Stream os) { GZipInputStream gis = new GZipInputStream(s); Stdio.CopyStream(gis, os); os.Flush(); }
/// <summary> /// GZip压缩 /// </summary> /// <param name="s">待压缩数据输入流</param> /// <param name="os">压缩后的数据输出流</param> public static void GZipCompress(Stream s, Stream os) { GZipOutputStream gos = new GZipOutputStream(os, 1024 * 4); Stdio.CopyStream(s, gos); gos.Finish(); }
public static void Write(Object value) { if (value != null) { Stdio.StdWrite(1, value.ToString()); } }
public static void Main(string[] args) { Console.WriteLine("Start Daemon"); // Init daemon var //DaemonVars.router.Start(); DaemonVars.router.Start(NEXCOMROBOT.MCAT.NexMotion_Define.DEV_TYPE_ETHERCAT); DaemonVars.stdout_stream.AutoFlush = true; // Start web Console.WriteLine("Start Web"); Thread th = new Thread(new ThreadStart(StartWeb)); th.Start(); // Start Stdio Console.WriteLine("Start Stdio"); Stdio.StartHandle(DaemonVars.router, DaemonVars.stdin_stream, DaemonVars.stdout_stream); // Shutdown web Console.WriteLine("Shutdown web"); th.Interrupt(); // Shutdown system Console.WriteLine("Shutdown system"); DaemonVars.router.Shudown(); Console.WriteLine("End Web"); }
/// <summary> /// 数据解压 /// </summary> /// <param name="s">待解压数据输入流</param> /// <param name="os">解压后的数据输出流</param> /// <param name="inflater">解压器</param> public static void Decompress(Stream s, Stream os, Inflater inflater) { InflaterInputStream iis = new InflaterInputStream(s, inflater, 1024 * 4); Stdio.CopyStream(iis, os); os.Flush(); }
private unsafe void CreateWriteAheadLogFile() { if (TrinityConfig.ReadOnly) { return; } string path = WriteAheadLogFilePath; Log.WriteLine(LogLevel.Info, "Creating write-ahead log file {0}", path); DropWriteAheadLogFile(); if (File.Exists(path)) { BackupWriteAheadLogFile(path); } void *new_fp = null; if (0 != Stdio._wfopen_s(out new_fp, path, "wb")) { Log.WriteLine(LogLevel.Error, "Cannot open the log file"); return; } LOG_FILE_HEADER header = LOG_FILE_HEADER.New(); GetTrinityImageSignature(&header.LOG_ASSOCIATED_IMAGE_SIGNATURE); CStdio.fwrite(&header, (ulong)sizeof(LOG_FILE_HEADER), 1, new_fp); CStdio.fflush(new_fp); _update_write_ahead_log_file(path, new_fp); }
static void DaemonHandler() { StreamReader src = DaemonVars.stdin_stream; StreamWriter dest = DaemonVars.stdout_stream; string command; while (true) { dest.Write("[Daemon-cmd]: "); command = src.ReadLine(); switch (command) { case "StdioStart": Stdio.StartHandle(DaemonVars.router, DaemonVars.stdin_stream, DaemonVars.stdout_stream); break; case "WebStart": break; case "WebShutdown": break; case "Shutdown": return; default: Console.WriteLine("[Daemon-ret]: invalid command format."); break; } } }
// Read a buffer of characters. public override int Read(char[] buffer, int index, int count) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (index < 0) { throw new ArgumentOutOfRangeException ("index", _("ArgRange_Array")); } if (count < 0) { throw new ArgumentOutOfRangeException ("count", _("ArgRange_Array")); } if ((buffer.Length - index) < count) { throw new ArgumentException(_("Arg_InvalidArrayRange")); } if (fd != -1) { return(Stdio.StdRead(fd, buffer, index, count)); } else { return(0); } }
// Flush this stream. public override void Flush() { if (fd != -1) { Stdio.StdFlush(fd); } }
public static void MoveBufferArea(int sourceLeft, int sourceTop, int sourceWidth, int sourceHeight, int targetLeft, int targetTop, char sourceChar, ConsoleColor sourceForeColor, ConsoleColor sourceBackColor) { lock (typeof(Console)) { SpecialMode(); int width, height; Stdio.GetBufferSize(out width, out height); if (sourceLeft < 0 || sourceLeft >= width) { throw new ArgumentOutOfRangeException ("sourceLeft", _("ArgRange_XCoordinate")); } if (sourceTop < 0 || sourceTop >= height) { throw new ArgumentOutOfRangeException ("sourceTop", _("ArgRange_YCoordinate")); } if (sourceWidth < 0 || (sourceLeft + sourceWidth) > width) { throw new ArgumentOutOfRangeException ("sourceWidth", _("ArgRange_Width")); } if (sourceHeight < 0 || (sourceTop + sourceHeight) > height) { throw new ArgumentOutOfRangeException ("sourceHeight", _("ArgRange_Height")); } if (targetLeft < 0 || targetLeft >= width) { throw new ArgumentOutOfRangeException ("targetLeft", _("ArgRange_XCoordinate")); } if (targetTop < 0 || targetTop >= height) { throw new ArgumentOutOfRangeException ("targetTop", _("ArgRange_YCoordinate")); } if ((((int)sourceForeColor) & ~0x0F) != 0) { throw new ArgumentException (_("Arg_InvalidColor"), "sourceForeColor"); } if ((((int)sourceBackColor) & ~0x0F) != 0) { throw new ArgumentException (_("Arg_InvalidColor"), "sourceBackColor"); } Stdio.MoveBufferArea(sourceLeft, sourceTop, sourceWidth, sourceHeight, targetLeft, targetTop, sourceChar, ((int)(sourceForeColor)) | (((int)(sourceBackColor)) << 4)); } }
public static ConsoleKeyInfo ReadKey(bool intercept) { lock (typeof(Console)) { SpecialMode(); } lock (readLock) { char ch; int key, modifiers; for (;;) { Stdio.ReadKey(out ch, out key, out modifiers); if (key == 0x1202) // Interrupt { HandleCancel(ConsoleSpecialKey.ControlC); continue; } else if (key == 0x1203) // CtrlBreak { HandleCancel(ConsoleSpecialKey.ControlBreak); continue; } if (!intercept && ch != '\0') { Stdio.StdWrite(1, ch); } return(new ConsoleKeyInfo (ch, (ConsoleKey)key, (ConsoleModifiers)modifiers)); } } }
// Close this stream. public override void Close() { if (fd != -1) { Stdio.StdClose(fd); fd = -1; } }
// Dispose this text reader. protected override void Dispose(bool disposing) { if (fd != -1) { Stdio.StdClose(fd); fd = -1; } }
// Reset the foreground and background colors to the defaults. public static void ResetColor() { lock (typeof(Console)) { SpecialMode(); currentAttrs = defaultAttrs; Stdio.SetTextAttributes(defaultAttrs); } }
public static void Write(char[] value) { if (value == null) { throw new ArgumentNullException("null"); } foreach (char ch in value) { Stdio.StdWrite(1, ch); } }
// Read the next character. public override int Read() { if (fd != -1) { return(Stdio.StdRead(fd)); } else { return(-1); } }
// Peek at the next character. public override int Peek() { if (fd != -1) { return(Stdio.StdPeek(fd)); } else { return(-1); } }
// Enable the "normal" input mode on the console. private static void NormalMode() { lock (typeof(Console)) { if (specialMode) { specialMode = false; Stdio.SetConsoleMode(Stdio.MODE_NORMAL); } } }
// Write data to this stream. public override void Write(byte[] buffer, int offset, int count) { ValidateBuffer(buffer, offset, count); if (fd == 1 || fd == 2) { Stdio.StdWrite(fd, buffer, offset, count); } else if (fd != -1) { throw new NotSupportedException (_("IO_NotSupp_Write")); } else { throw new ObjectDisposedException(_("IO_StreamClosed")); } }
// Read data from this stream. public override int Read(byte[] buffer, int offset, int count) { ValidateBuffer(buffer, offset, count); if (fd == 0) { return(Stdio.StdRead(fd, buffer, offset, count)); } else if (fd != -1) { throw new NotSupportedException (_("IO_NotSupp_Read")); } else { throw new ObjectDisposedException(_("IO_StreamClosed")); } }
public static void Beep(int frequency, int duration) { if (frequency < 37 || frequency > 32767) { throw new ArgumentOutOfRangeException ("frequency", _("ArgRange_BeepFrequency")); } if (duration <= 0) { throw new ArgumentOutOfRangeException ("duration", _("ArgRange_PositiveNonZero")); } lock (typeof(Console)) { SpecialMode(); Stdio.Beep(frequency, duration); } }
static void Main(string[] args) { ProgramTools.Setup(); var config = new Config(); ExecutableTools.LogArgs(new StderrWriteLine(), args, (arg) => { ConfigTools.SetProperty(config, arg); }); if (!config.Daemon) { Logger.TRACE = new StderrWriteLine(); } Stdio.SetStatus("Ready"); var line = Stdio.ReadLine(); while (line != null) { Logger.Trace("> {0}", line); if (line == "ping") { Stdio.WriteLine("pong"); Logger.Trace("< pong"); } //throw Exception Message if (line.StartsWith("throw")) { throw new Exception(line.Substring(6)); } if (line == "exit!") { return; } line = Stdio.ReadLine(); } Logger.Trace("Stdin closed"); Environment.Exit(0); }
// Enable the "special" character-at-a-time input mode on the console. private static void SpecialMode() { lock (typeof(Console)) { if (!specialMode) { specialMode = true; if (treatControlCAsInput) { Stdio.SetConsoleMode(Stdio.MODE_RAW); } else { Stdio.SetConsoleMode(Stdio.MODE_CBREAK); } defaultAttrs = Stdio.GetTextAttributes(); currentAttrs = defaultAttrs; } } }
// Set the cursor position. public static void SetCursorPosition(int left, int top) { lock (typeof(Console)) { SpecialMode(); int width, height; Stdio.GetBufferSize(out width, out height); if (left < 0 || left >= width) { throw new ArgumentOutOfRangeException ("left", _("ArgRange_XCoordinate")); } if (top < 0 || top >= height) { throw new ArgumentOutOfRangeException ("top", _("ArgRange_YCoordinate")); } Stdio.SetCursorPosition(left, top); } }
// Read a line from the standard input stream. public static String ReadLine() { StringBuilder builder = new StringBuilder(); int ch; NormalMode(); while ((ch = Stdio.StdRead(0)) != -1 && ch != '\n') { if (ch != '\r') { builder.Append((char)ch); } } if (ch == -1 && builder.Length == 0) { return(null); } else { return(builder.ToString()); } }
// Set the buffer size. public static void SetBufferSize(int width, int height) { lock (typeof(Console)) { SpecialMode(); int wleft, wtop, wwidth, wheight; Stdio.GetWindowSize (out wleft, out wtop, out wwidth, out wheight); if (width <= 0 || width > 32767 || width < (wleft + wwidth)) { throw new ArgumentOutOfRangeException ("width", _("ArgRange_Width")); } if (height <= 0 || height > 32767 || height < (wtop + wheight)) { throw new ArgumentOutOfRangeException ("height", _("ArgRange_Height")); } Stdio.SetBufferSize(width, height); } }
public static void Write(char[] value, int index, int count) { if (value == null) { throw new ArgumentNullException("null"); } if (index < 0 || index > value.Length) { throw new ArgumentOutOfRangeException ("index", _("ArgRange_StringIndex")); } if (count < 0 || count > (value.Length - index)) { throw new ArgumentOutOfRangeException ("count", _("ArgRange_StringRange")); } while (count > 0) { Stdio.StdWrite(1, value[index]); ++index; --count; } }
// Set the window position. public static void SetWindowPosition(int left, int top) { lock (typeof(Console)) { SpecialMode(); int width, height; Stdio.GetBufferSize(out width, out height); int wleft, wtop, wwidth, wheight; Stdio.GetWindowSize (out wleft, out wtop, out wwidth, out wheight); if (left < 0 || (left + wwidth) > width) { throw new ArgumentOutOfRangeException ("left", _("ArgRange_XCoordinate")); } if (top < 0 || (left + wheight) > height) { throw new ArgumentOutOfRangeException ("left", _("ArgRange_YCoordinate")); } Stdio.SetWindowSize(left, top, wwidth, wheight); } }
/// <summary> /// Opens the log file in read mode and replay the actions inside, /// and when the logs are synced, save the storage to an image, then /// drop the old log file. /// This method always target [PRIMARY] storage slot. /// </summary> private void _LoadWriteAheadLogFile() { lock (m_lock) { if (TrinityConfig.ReadOnly) { return; } string path = _WriteAheadLogFilePath(); Log.WriteLine(LogLevel.Debug, "Loading write-ahead log file {0}", path); LOG_FILE_HEADER header = LOG_FILE_HEADER.New(); TRINITY_IMAGE_SIGNATURE current_sig = new TRINITY_IMAGE_SIGNATURE(); LOG_RECORD_HEADER record_header = new LOG_RECORD_HEADER(); long record_cnt = 0; byte[] cell_buff = new byte[128]; void * new_fp = null; bool ver_compatible = true; bool img_compatible = true; GetTrinityImageSignature(¤t_sig); _DropWriteAheadLogFile(); if (!File.Exists(path)) { Log.WriteLine(LogLevel.Debug, "Write ahead log doesn't exist, quit loading."); return; } if (0 != Stdio._wfopen_s(out new_fp, path, "rb")) { Log.WriteLine(LogLevel.Fatal, "Cannot open write ahead log for read. Exiting."); goto load_fail; } /* Read log header */ if (1 != CStdio.C_fread(&header, (ulong)sizeof(LOG_FILE_HEADER), 1, new_fp)) { Log.WriteLine(LogLevel.Fatal, "Cannot read write-ahead-log header. Exiting."); goto load_fail; } ver_compatible = header.CompatibilityCheck(); img_compatible = Memory.Compare((byte *)&header.LOG_ASSOCIATED_IMAGE_SIGNATURE, (byte *)¤t_sig, sizeof(TRINITY_IMAGE_SIGNATURE)); if (!ver_compatible || !img_compatible) { /* The log is not ours. Ignore if it's empty. */ if (0 == CStdio.C_feof(new_fp)) { Log.WriteLine(LogLevel.Warning, "Found incompatible empty write-ahead-log file, ignoring."); CStdio.C_fclose(new_fp); return; } else if (this.CellCount != 0) { goto load_incompatible; } /* Otherwise, (CellCount is 0), it indicates that we're recovering from a fresh start. */ } Log.WriteLine(LogLevel.Info, "Reading log file."); while (1 == CStdio.C_fread(&record_header, (ulong)sizeof(LOG_RECORD_HEADER), 1, new_fp)) { if (record_header.CONTENT_LEN >= 0) { /* Ensure space for the cell buffer */ if (record_header.CONTENT_LEN > cell_buff.Length) { if (record_header.CONTENT_LEN < 1 << 20) { cell_buff = new byte[record_header.CONTENT_LEN * 2]; } else { cell_buff = new byte[record_header.CONTENT_LEN]; } } fixed(byte *p_buff = cell_buff) { if (1 != CStdio.C_fread(p_buff, (ulong)record_header.CONTENT_LEN, 1, new_fp) && record_header.CONTENT_LEN != 0) { Log.WriteLine(LogLevel.Error, "Incomplete write-ahead-log record at the end of file"); break; } if (false == LOG_RECORD_HEADER.CWriteAheadLogValidateChecksum(&record_header, p_buff)) { Log.WriteLine(LogLevel.Fatal, "Checksum mismatch for log record #{0}", record_cnt); goto load_fail; } this.SaveCell(record_header.CELL_ID, p_buff, record_header.CONTENT_LEN, record_header.CELL_TYPE); } } else /* if (record_header.CONTENT_LEN < 0) */ { if (false == LOG_RECORD_HEADER.CWriteAheadLogValidateChecksum(&record_header, null)) { Log.WriteLine(LogLevel.Fatal, "Checksum mismatch for log record #{0}", record_cnt); goto load_fail; } this.RemoveCell(record_header.CELL_ID); } ++record_cnt; } goto load_success; //////////////////////////////////////// load_incompatible: if (ver_compatible) { Log.WriteLine(LogLevel.Fatal, "The log file is incompatible with the current version. Cannot recover."); } if (img_compatible) { Log.WriteLine(LogLevel.Fatal, "The log file has a different signature than the current image. Cannot recover."); } goto load_fail; //////////////////////////////////////// load_success: Log.WriteLine(LogLevel.Info, "Write-ahead-log successfully loaded. Recovered {0} records.", record_cnt); if (0 != CStdio.C_fclose(new_fp)) { Log.WriteLine(LogLevel.Error, "Cannot close the write-ahead-log file. Logging disabled."); return; } /* Only save storage when the log is not empty. */ if (record_cnt == 0 || TrinityErrorCode.E_SUCCESS == SaveStorage()) { /* Save storage succeeded. Dropping old logs now. */ try { File.Delete(path); } catch (Exception ex) { Log.WriteLine(LogLevel.Error, "Failed to delete the old logs: {0}", ex); } } else { /* Save storage failed. */ Log.WriteLine(LogLevel.Fatal, "Failed to save the recovered storage. The old log is retained"); goto load_fail; } return; //////////////////////////////////////// load_fail: if (new_fp != null) { CStdio.C_fclose(new_fp); } Environment.Exit(-1); } }