.NET跨平台实践:.NetCore、.Net5/6 Linux守护进程设计
幾年前,我寫過兩篇關(guān)于用C#開發(fā)Linux守護(hù)進(jìn)程的技術(shù)文章,分別是《.NET跨平臺(tái)實(shí)踐:用C#開發(fā)Linux守護(hù)進(jìn)程.NET跨平臺(tái)實(shí)踐:再談?dòng)肅#開發(fā)Linux守護(hù)進(jìn)程 — 完整篇
這就是本文的初衷。
關(guān)于Linux Daemon程序的原理之類的,已經(jīng)在之前的兩篇文章中得到了一些表現(xiàn),因此,本文就直接上代碼,不再在高大上的理論中去兜圈子了。
using System; using System.Threading; using System.Timers; using System.Runtime.InteropServices; using System.IO; using System.Text;/************************************************* .Net Core/.Net5+ Linux Daemon示例,作者宇內(nèi)流云 ************************************************/namespace daemon {class Program{static unsafe void Main(string[] args){// 進(jìn)入守護(hù)狀態(tài)int pid = fork();if (pid != 0) exit(0);setsid();pid = fork();if (pid != 0) exit(0);umask(0);// 關(guān)閉所有打開的文件描述符int fd_nul = open("/dev/null", 0);for (var i = 0; i <= fd_nul; i++){if (i < 3)Dup2(fd_nul, i);elseclose(i);}// 進(jìn)入主方法 // (本示例的功能很簡(jiǎn)單,就是定時(shí)向某個(gè)文件寫入點(diǎn)內(nèi)容) DaemonMain(args);}/// <summary>/// Daemon工作狀態(tài)的主方法/// </summary>/// <param name="aargs"></param>static void DaemonMain(string[] aargs){//啟動(dòng)一個(gè)線程去處理一些事情(new Thread(DaemonWorkFunct) { IsBackground = true }).Start();//daemon時(shí),控制臺(tái)輸入、輸出流已經(jīng)關(guān)閉// 因此,請(qǐng)不要再用Console.Write/Read等方法//阻止daemon進(jìn)程退出(new AutoResetEvent(false)).WaitOne();}static FileStream fs;static int count = 0;static void DaemonWorkFunct(){try{fs = File.Open(Path.Combine("/tmp", "daemon.txt"), FileMode.OpenOrCreate);}catch{exit(1);return;}var t = new System.Timers.Timer() { Interval = 1000 };t.Elapsed += OnElapsed;t.Start();}private static void OnElapsed(object sender, ElapsedEventArgs e){var s = DateTime.Now.ToString("yyy-MM-dd HH:mm:ss") + "\n";var b = Encoding.ASCII.GetBytes(s);fs.Write(b, 0, b.Length);fs.Flush();count++;if (count > 100){fs.Close();fs.Dispose();exit(0);}}[DllImport("libc", SetLastError = true)]static extern int fork();[DllImport("libc", SetLastError = true)]static extern int setsid();[DllImport("libc", SetLastError = true)]static extern int umask(int mask);[DllImport("libc", SetLastError = true)]static extern int open([MarshalAs(UnmanagedType.LPStr)] string pathname, int flags);[DllImport("libc", SetLastError = true)]static extern int close(int fd);[DllImport("libc", SetLastError = true)]static extern int exit(int code);[DllImport("libc", EntryPoint = "dup2", SetLastError = true)]static extern int Dup2(int oldfd, int newfd);} }以上代碼就是Linux環(huán)境中,.NetCore或.Net5以上版本的.net程序,以純代碼方式使自身成為標(biāo)準(zhǔn)的Linux守護(hù)進(jìn)程的示例代碼,你完全可以將它關(guān)鍵部分借用到自己的真實(shí)項(xiàng)目中。使用中如果有什么問題或建議,請(qǐng)加入本人的QQ群作進(jìn)一點(diǎn)交流。
注:本文為?宇內(nèi)流云?(郵箱:j66x@163.com)原創(chuàng)作品,用c#開發(fā)原生的Linux守護(hù)進(jìn)程相關(guān)技術(shù)及代碼亦屬本人首發(fā),如需轉(zhuǎn)載,請(qǐng)注明出處和作者,同時(shí),沒有得到本人親自同意,本文關(guān)鍵代碼不得被“借鑒”到其他紙質(zhì)作品中。
總結(jié)
以上是生活随笔為你收集整理的.NET跨平台实践:.NetCore、.Net5/6 Linux守护进程设计的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Workflow Core + asp.
- 下一篇: 云原生开发框架dapr环境搭建:CLI安