Skip to content

Instantly share code, notes, and snippets.

@MikuAuahDark
Created November 16, 2022 16:35
Show Gist options
  • Save MikuAuahDark/3fae0c36b878c4d29d8d03eceab3916c to your computer and use it in GitHub Desktop.
Save MikuAuahDark/3fae0c36b878c4d29d8d03eceab3916c to your computer and use it in GitHub Desktop.
How to Run WSL on Logon

Run WSL on Logon

  1. Compile runsilent.c in Windows
  2. Compile dummy.c in Linux
  3. Import the task with schtasks in Windows, modify the path as needed before importing.

Notes

  • When you shutdown the WSL (with wsl --shutdown), to start it again in background, run schtasks /run /tn:wslon. No administrator privileges is required.
  • If you have more than 1 distro and want them to start too, you need to:
    1. Perform step 2 on each distro. Copying existing binary may work, but there's no guarantee.
    2. Add additional <Exec></Exec> in the XML, or add "Start a program" action in Task Scheduler.
    3. Adjust the WSL command-line as needed (by adding -d <distro>.
/* clang -O3 -o donothing.elf dummy.c */
/* sudo cp donothing.elf /donothing.elf */
/* sudo chmod +x /donothing.elf */
#include <signal.h>
#include <unistd.h>
static volatile sig_atomic_t flag = 0;
static void shandler(int signum)
{
flag = 1;
}
int main()
{
signal(SIGINT, shandler);
signal(SIGTERM, shandler);
while (flag == 0)
sleep(60);
return 0;
}
<?xml version="1.0" encoding="UTF-16"?>
<!-- NOTE: This file MUST be saved as UTF-16 LE with BOM, otherwise Task Scheduler will reject this file! !-->
<!-- Don't import it blindly. Replace stuff as needed, mainly the variables, the runsilent path, and the donothing.elf path !-->
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
<RegistrationInfo>
<URI>\wslon</URI>
</RegistrationInfo>
<Settings>
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
<StopIfGoingOnBatteries>true</StopIfGoingOnBatteries>
<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
<RestartOnFailure>
<Count>999</Count>
<Interval>PT1M</Interval>
</RestartOnFailure>
<StartWhenAvailable>true</StartWhenAvailable>
<IdleSettings>
<StopOnIdleEnd>true</StopOnIdleEnd>
<RestartOnIdle>false</RestartOnIdle>
</IdleSettings>
</Settings>
<Triggers>
<LogonTrigger>
<UserId>%COMPUTERNAME%\%USERNAME%</UserId>
</LogonTrigger>
</Triggers>
<Actions Context="Author">
<Exec>
<Command>C:\path\to\runsilent.exe</Command>
<!-- If you're in Windows 10, replace the WSL path to "C:\Windows\System32\wsl.exe" (without quotes) !-->
<Arguments>%USERPROFILE%\AppData\Local\Microsoft\WindowsApps\wsl.exe /donothing.elf</Arguments>
</Exec>
</Actions>
</Task>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment