Win10 WSL2 Ubuntu Linux 设置程序开机启动 您所在的位置:网站首页 applecare订阅退款 Win10 WSL2 Ubuntu Linux 设置程序开机启动

Win10 WSL2 Ubuntu Linux 设置程序开机启动

2023-07-25 16:38| 来源: 网络整理| 查看: 265

Win10 WSL2 Ubuntu Linux 设置程序开机启动

由于WSL2里面不能用systemd,所以WSL2里面的程序启动需要借助外部脚本 大致过程如下:

win10开机 =====> win10开机脚本 =====> Linux子系统脚本 =====> 启动Linux程序

我们以Mysql为样例

安装配置Mysql

具体安装过程不叙述,安装配置完成之后,可以通过

service mysql start

即可

编写 启动Mysql 脚本

在 /etc 目录下新增 init.wsl 文件

sudo vim /etc/init.wsl

输入以下内容,并保存

#! /bin/sh service mysql stop usermod -d /var/lib/mysql/ mysql service mysql start

由于mysql异常关机后启动,会有错误提示,这里先停止,再启动

编写win10开机脚本

该脚本的目的是运行 linux子系统中的脚本。 可以用VBS执行

Set ws = WScript.CreateObject("WScript.Shell") ws.run "wsl -d Ubuntu-20.04 -u root /etc/init.wsl"

将运行另存为 linux-start.vbs,并拷贝到 C:\Users\当前用户\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup 目录(运行 shell:startup,可以直接打开该目录)

优化开机脚本,去除讨厌的黑框框

该脚本再每次开机执行时都会弹出烦人的黑框框,除去方式有很多种,这里我使用C# Winform程序作为开机启动linux服务程序。

using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Windows.Forms; namespace linux_start { static class Program { /// /// 应用程序的主入口点。 /// [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); try { var cmd = "wsl -d Ubuntu-20.04 -u root /etc/init.wsl"; RunCmd(cmd); } catch { } // 不需要运行界面 //Application.Run(new Form1()); } static void RunCmd(string strCMD) { //创建一个进程 Process p = new Process(); p.StartInfo.FileName = "cmd.exe"; p.StartInfo.UseShellExecute = false;//是否使用操作系统shell启动 p.StartInfo.RedirectStandardInput = true;//接受来自调用程序的输入信息 p.StartInfo.RedirectStandardOutput = true;//由调用程序获取输出信息 p.StartInfo.RedirectStandardError = true;//重定向标准错误输出 p.StartInfo.CreateNoWindow = true;//不显示程序窗口 p.Start();//启动程序 //向cmd窗口发送输入信息 p.StandardInput.WriteLine(strCMD + "&exit"); p.StandardInput.AutoFlush = true; //获取cmd窗口的输出信息 string output = p.StandardOutput.ReadToEnd(); //等待程序执行完退出进程 p.WaitForExit(); p.Close(); } } }

该程序关键点在于 ,该方式可以 执行脚本而不弹出黑框框窗口

p.StartInfo.UseShellExecute = false;//是否使用操作系统shell启动 p.StartInfo.CreateNoWindow = true;//不显示程序窗口


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有