This repository has been archived on 2025-09-14. You can view files and clone it, but cannot push or open issues or pull requests.
Files
zhangyang-zerotierone/windows/ZeroTierOneService/Service.cs

111 lines
3.2 KiB
C#
Raw Normal View History

2014-01-20 17:03:15 -08:00
using System;
2014-01-21 09:18:12 -08:00
using System.IO;
2014-01-20 17:03:15 -08:00
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Threading;
2014-01-20 17:03:15 -08:00
namespace ZeroTierOneService
{
public partial class Service : ServiceBase
{
public Service()
{
InitializeComponent();
2014-01-21 09:18:12 -08:00
this.ztHome = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + Path.DirectorySeparatorChar + "ZeroTier" + Path.DirectorySeparatorChar + "One";
this.ztUpdatesFolder = this.ztHome + Path.DirectorySeparatorChar + "updates.d";
this.ztBinary = this.ztHome + Path.DirectorySeparatorChar + (Environment.Is64BitOperatingSystem ? "zerotier-one_x64.exe" : "zerotier-one_x86.exe");
this.ztService = null;
this.ztKiller = null;
2014-01-20 17:03:15 -08:00
}
protected override void OnStart(string[] args)
{
startZeroTierDaemon();
2014-01-20 17:03:15 -08:00
}
protected override void OnStop()
{
stopZeroTierDaemon();
2014-01-20 17:03:15 -08:00
}
2014-01-21 09:18:12 -08:00
private void startZeroTierDaemon()
2014-01-21 09:18:12 -08:00
{
if (ztService != null)
return;
ztService = new Process();
try
{
ztService.StartInfo.UseShellExecute = false;
ztService.StartInfo.FileName = ztBinary;
ztService.StartInfo.Arguments = "";
ztService.StartInfo.CreateNoWindow = true;
ztService.Exited += ztService_Exited;
ztService.Start();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
ztService = null;
}
2014-01-21 09:18:12 -08:00
}
private void stopZeroTierDaemon()
2014-01-21 09:18:12 -08:00
{
while (ztKiller != null)
Thread.Sleep(250);
ztKiller = new Process();
try
{
ztKiller.StartInfo.UseShellExecute = false;
ztKiller.StartInfo.FileName = ztBinary;
ztKiller.StartInfo.Arguments = "-q terminate ServiceShutdown";
ztKiller.StartInfo.CreateNoWindow = true;
ztKiller.Exited += ztKiller_Exited;
ztKiller.Start();
}
catch (Exception e)
{
ztKiller = null;
}
int waited = 0;
while (ztKiller != null)
{
Thread.Sleep(250);
if (++waited > 100)
break;
}
2014-01-21 09:18:12 -08:00
if (ztService != null)
{
ztService.Kill();
ztService = null;
}
}
// Event generated when ztService exits
2014-01-21 09:18:12 -08:00
private void ztService_Exited(object sender, System.EventArgs e)
{
ztService = null;
2014-01-21 09:18:12 -08:00
}
// Event generated when ztKiller is done
private void ztKiller_Exited(object sender, System.EventArgs e)
{
ztKiller = null;
}
2014-01-21 09:18:12 -08:00
private string ztHome;
private string ztUpdatesFolder;
private string ztBinary;
private volatile Process ztService;
private volatile Process ztKiller;
2014-01-20 17:03:15 -08:00
}
}