Linux application in windows

Компонент WSL (Windows Subsystem for Linux или Подсистема Windows для Linux) появился в Windows 10 и с тех пор постоянно развивается. Одна из новых возможностей, которую кто-то из пользователей мог пропустить — возможность простого и удобного запуска программ Linux с GUI прямо в ОС Windows.

В этом материале — пример быстрой установки всего необходимого и запуска приложений с графическим интерфейсом в Windows 11 и 10 и дополнительная информация, которая может оказаться полезной.

Установка WSL, дистрибутива Linux и приложений

Установить WSL и нужный дистрибутив можно разными способами:

  • Включив необходимые компоненты в дополнительных компонентах Windows и загрузив дистрибутив в Microsoft Store (подробнее).
  • Почти автоматически в командной строке.

Далее будет рассмотрен второй вариант, как более быстрый в контексте рассматриваемой темы.

Для установки WSL и конкретного дистрибутива Linux достаточно выполнить следующие шаги:

  1. Запустите командную строку от имени администратора, введите команду
    wsl --install

    и нажмите Enter, дождитесь завершения выполнения команды.

    Установка WSL в командной строке

  2. Перезагрузите компьютер и снова зайдите в командную строку. Если на первом шаге была также произведена установка Ubuntu (в некоторых версиях Windows устанавливается автоматически), завершите установку с помощью
    wsl --install Ubuntu

    В процессе потребуется задать имя пользователя и пароль.

  3. Если требуется другой дистрибутив или автоматическая установка не выполнялась, по порядку введите команды (первая покажет список доступных дистрибутивов, во второй укажите имя дистрибутива из левого столбца):
    wsl --list --online
    wsl --install NAME
    Список дистрибутивов в WSL

Готово, дистрибутив установлен, а поддержка графического интерфейса приложений в WSL текущих версий включается автоматически (ранее этого можно было добиться лишь обходными путями, по умолчанию приложения работали только в режиме терминала), переходим к установке приложений:

  1. Введите команду
    sudo apt-get update

    также можно использовать apt вместо apt-get. Дождитесь обновления репозиториев.

  2. Для установки приложения по его имени введите команду
    sudo apt-get install ИМЯ_ПРИЛОЖЕНИЯ -y
    Установка приложений в WSL Windows

  3. Приложение будет установлено и появится в меню «Пуск» Windows (в папке соответствующего дистрибутива), откуда его можно будет запустить:
    Приложения Linux в меню Пуск Windows 11

  4. Тем же способом можно установить и другие необходимые приложения, а для их удаления используйте команду
    sudo apt-get remove ИМЯ_ПРИЛОЖЕНИЯ

Результат: приложения Linux с графическим интерфейсом исправно работают прямо в Windows:

Приложения Linux с графическим интерфейсом работают в Windows

Делают это со звуком, ускорением графики OpenGl, пробросом локальных дисков.

При желании вы даже можете установить менеджер пакетов с графическим интерфейсом (своего рода «магазин приложений»). Например, мне удалось добиться вполне исправной работы Gnome Software:

  1. Устанавливаем с помощью команды в WSL
    sudo apt install gnome-software -y
  2. Изменяем свойства ярлыка, добавленного в меню «Пуск» (правый клик по ярлыку в меню Пуск — перейти к расположению файла — открыть свойства ярлыка), заменив поле объект на (пример для Ubuntu)
    "C:\Program Files\WSL\wslg.exe" -d Ubuntu -u root sudo gnome-software

    Подобным же способом можно «заставить» запускаться от имени суперпользователя с ярлыков Windows и другие программы.

    Запуск ярлыка WSLG от имени ROOT

  3. Пользуемся для установки, обновления и удаления приложений Linux прямо в Windows, в графическом интерфейсе:
    Пакеты приложений в Gnome Software в Windows

Подробная техническая информация о том, как именно работают Linux-приложения с GUI доступна на GitHub проекта WSLg, с помощью которого реализована соответствующая функциональность.

Running Linux GUI Apps on Windows with WSL2: A Guide



Published




6 min read

Title: How to Run Linux GUI Apps With WSL2 on Windows

In recent years, the Windows Subsystem for Linux (WSL) has dramatically changed how developers and enthusiasts interact with Linux on a Windows machine. The advent of WSL2 introduced significant improvements, allowing users to embrace a more authentic Linux experience without the need for dual-booting or utilizing virtual machines. One of the most exciting developments in WSL2 is its capability to run Linux graphical user interface (GUI) applications directly on Windows. This comprehensive guide is designed to help you navigate this process, explaining each step in detail while addressing potential challenges along the way.

Understanding WSL2

Before we dive into the details of running Linux GUI applications, it’s crucial to understand what WSL2 is and how it differs from its predecessor, WSL. WSL2 is a lightweight virtualization environment that runs a real Linux kernel alongside your Windows operating system. This change offers numerous advantages, including improved performance, compatibility with more Linux applications, and access to the complete system call interface.

WSL2 also features a more efficient file system, which allows you to access Linux files as if they were part of your Windows file system. This significantly enhances the usability of both systems, making it easier for developers to manage projects that rely on both Windows and Linux.

Installing WSL2

To run GUI applications, you’ll first need to ensure that WSL2 is installed and set up correctly on your Windows machine. Here’s how to do it:

  1. Enable WSL:

    1. Open PowerShell as an administrator.
    2. Run the command:
      wsl --install
    3. This command will enable the required components, download the latest Linux kernel, and set your default distribution to Ubuntu.
  2. Check your installation:
    To verify that WSL has been installed successfully, run:

    wsl -l -v

    This will list all installed distributions and their WSL versions.

  3. Update WSL kernel:
    Make sure you have the latest WSL kernel installed. You can download it from the official Microsoft website if necessary.

  4. Set WSL2 as your default version:
    To ensure that any new distributions you install will default to WSL2:

    wsl --set-default-version 2
  5. Install a Linux distribution:
    You can install distributions directly from the Microsoft Store. Open the Store, search for Ubuntu or your preferred Linux distro, and install it. Launch it, and you’ll have a terminal window where you can begin working.

Installing GUI Applications

Once you have set up WSL2, you can begin installing GUI applications. This guide will focus on Ubuntu, as it’s one of the most popular distributions among WSL users.

  1. Update your package lists:
    Before installing any software, ensure your package lists are up to date:

    sudo apt update
    sudo apt upgrade
  2. Installing a Desktop Environment (Optional):
    While WSL2 can run GUI applications without a full desktop environment, installing a lightweight desktop environment can enhance your experience. Xfce is a good choice:

    sudo apt install xfce4
  3. Install an X Server for Windows:
    To render GUI applications on Windows, you need an X Server. Some popular options are:

    • VcXsrv: A free and open-source X server for Windows.
    • X410: A paid option available on the Microsoft Store with additional features.

    For this guide, we’ll walk through the setup with VcXsrv:

    a. Download and Install VcXsrv:
    Visit the VcXsrv website and download the installer. Run the installation, and accept the defaults.

    b. Run VcXsrv:
    Launch VcXsrv using the “XLaunch” application. Follow the prompts to configure it:

    • Choose «Multiple windows.»
    • Select «Start no client.»
    • Check «Disable access control» (this allows all connections—change this setting based on your security needs).
    • Click «Finish» to start the server.
  4. Configure the DISPLAY environment variable:
    After starting VcXsrv, you need to set your DISPLAY variable in the WSL terminal. Run:

    export DISPLAY=$(cat /etc/resolv.conf | grep nameserver | awk '{print $2}'):0

    To make this variable persist across sessions, add the export command to your .bashrc or .bash_profile in your home directory.

  5. Installing GUI applications:
    Now that everything is set up, you can install GUI applications. For instance, install gedit (a text editor) and gnome-terminal:

    sudo apt install gedit gnome-terminal
  6. Running GUI applications:
    Launch your installed GUI applications directly from the WSL terminal. For example, type:

    gedit

    You may see the gedit window pop up on your Windows desktop.

Using Wayland and New Features

With the upcoming improvements in WSL, including support for Wayland, the process of running GUI applications is becoming even simpler. Wayland is an alternative to the X Window System and promises better performance and security.

  • For those who are using Wayland applications, ensure you have the appropriate setup with X server or consider using a Wayland-Compatible X Server in the future as it becomes available.

Troubleshooting Common Issues

While running GUI applications through WSL2 is generally straightforward, you might encounter a few issues. Here are some common problems and their solutions:

  1. Application Not Displaying:
    Ensure that your X server is running and that the DISPLAY variable is set correctly. If you installed your X server with a non-default configuration, ensure it matches your settings.

  2. Permission Denied Errors:
    If you’re experiencing any permission issues, ensure you have the correct access permissions for your files and directories. Also, check that your X server is configured to allow connections.

  3. Performance Issues:
    Some applications may not perform optimally due to the overhead of running them through WSL. Ensure you keep your applications up to date and consider using newer alternatives designed for performance.

  4. Fonts Not Displaying Properly:
    Sometimes, fonts may not render correctly. You can install additional font packages to ensure better display support:

    sudo apt install xfonts-100dpi xfonts-75dpi

Extending Functionality With Additional Tools

Depending on your needs, you may want to use additional tools or configurations to make your Linux GUI experience even better:

  1. Installing Additional Applications:
    You can find a vast repository of applications in the Ubuntu package manager. Use apt search to find and install more tools as needed.

  2. Using Docker with GUI applications:
    If you utilize Docker, you can run GUI applications from inside Docker containers as well, using the same procedures for DISPLAY variable configuration and X server.

  3. Integrating with Windows Applications:
    You can share the clipboard, drag and drop files, and run Windows and Linux applications side-by-side to create a seamless workflow. Using tools like Visual Studio Code, you can effectively work on projects that span both environments.

  4. Developing with VS Code:
    Visual Studio Code has great extensions that support WSL, enabling you to run commands and manage files directly from within your Windows development environment.

  5. Maintaining Performance and Stability:
    Regularly maintain your WSL installation by updating packages, removing unnecessary applications, and monitoring system performance.

Conclusion

Running Linux GUI applications on Windows through WSL2 opens up a world of possibilities for developers, system administrators, and enthusiasts alike. The flexibility of combining both ecosystems can significantly enhance productivity and efficiency in any workflow. As the capabilities of WSL2 continue to evolve, users can expect even more features, improved performance, and ease of integration with Windows.

In this guide, we’ve covered the steps to set up WSL2, install GUI applications, and troubleshoot common issues. By following these instructions, you can enjoy the best of both worlds—harnessing the power of Linux applications while working seamlessly within the Windows environment.

As you gain experience with WSL2, don’t hesitate to explore the extensive ecosystems that both Linux and Windows offer. The fusion of these two worlds could lead to innovative solutions, unforgettable projects, and even new business opportunities. Happy coding and exploring!

Среда Windows Subsystem for Linux (WSL) позволяет запускать нативные приложения, писать скрипты, выполнять команды и скрипты Linux непосредственно из Windows без использования эмуляторов или развертывания выделенных виртуальных машин. Актуальной версией среды является WSL 2, в которой используется полноценное ядро Linux (версия ядра 5.15) и обеспечивает полную совместимость с системными вызовами. Образ ядра Linux в WSL представляет собой легкую виртуальную машину, для запуска которой не нужно устанавливать полноценную роль Hyper-V.

Содержание:

  • Как установить Windows Subsystem for Linux (WSL2)?
  • WSL: Установка дистрибутива Linux в Windows
  • Команды для управления WSL в Windows
  • Использование Linux в среде WSL

Вы можете запустить WSL 2:

  • Во всех версиях Windows 10, начиная с 1903, а также в Windows 11 и Windows Server 2022;
  • В настройка BIOS/UEFI компьютера должна быть включена поддержка аппаратной виртуализации: Intel VT (Intel Virtualization Technology) или AMD-V (SVM Mode).

Как установить Windows Subsystem for Linux (WSL2)?

Компонент WSL по умолчанию отключен в Windows. Современных дистрибутивах Windows 10 и Windows 11 для установки среды WSL достаточно выполнить команду:

wsl --install

Этак команда автоматически включит все необходимые компоненты Windows, необходимые для работы WSL, установить обновление ядра Linux для WSL2, загрузит дистрибутив Ubuntu (по-умолчанию) и установит его в WSL.

команда для быстрой установки wsl в windows 10 и 11

Осталось перезагрузить компьютер, и вы можете запускать среду WSL!

Вы можете установить для WSL другой дистрибутив Linux. Выведите список доступных дистрибутивов:

wsl --list --online

Укажите имя дистрибутива Linux, который установить в WSL. Например:

wsl --install -d kali-linux

список доступных дистрибутивов Linux для WSL

Если в BIOS/UEFI компьютера не включена виртуализация, при установке WSL вы получите ошибку:

Installation failed with error 0x80070003 or error 0x80370102” it means that Bios Level Virtualization is not enabled on your computer.

Вы можете установить WSL2 в Windows вручную. Для этого придется вручную последовательно выполнить все этапы, который команда wsl —install запускала автоматически:

  1. Установить WSL
  2. Включить компонент виртуалзации VirtualMachinePlatform
  3. Установить ядро WSL 2
  4. Скачать и установить дистрибутив Linux для WSL

Сначала установите следующие компоненты Windows:

Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux
Enable-WindowsOptionalFeature -Online -FeatureName VirtualMachinePlatform

установить компонент wsl в windows вручную

Перезагрузите компьютер.

Скачаем и установим обновление ядра Linux для WSL2 (WSL2 Linux kernel update package for x64 machines — https://wslstorestorage.blob.core.windows.net/wslblob/wsl_update_x64.msi). Можете скачать пакет вручную или с помощью PowerShell:

Invoke-WebRequest -Uri https://wslstorestorage.blob.core.windows.net/wslblob/wsl_update_x64.msi -OutFile "$($env:userprofile)\Downloads\wsl_update_x64.msi" -UseBasicParsing
Invoke-Item "$($env:userprofile)\Downloads\wsl_update_x64.msi"
rm "$($env:userprofile)\Downloads\wsl_update_x64.msi"

windows subsyste for linux update setup

Еще раз перезагрузите компьютер и назначьте версию WSL 2 в качестве среды по-умолчанию:

wsl --set-default-version 2

wsl2 назначить по умолчанию

WSL: Установка дистрибутива Linux в Windows

После того, как ядро WSL установлено в Windows, вы можете установить один или несколько дистрибутивов Linux на компьютер.

Можно установить пакет с дистрибутивом Linux через Microsoft Store. Доступны следующие дистрибутивы:

  • Ubuntu
  • Debian
  • Kali Linux
  • OpenSUSE
  • Oracle Linux
  • SUSE Linux Enterprise Server
  • Fedora

Найдите нужную версию дистрибутива в Store и установите ее, нажав кнопку Получить (Get).

скачать образ linux для wsl из microsoft store

Если у вас отключен Windows Store, вы хотите установить дистрибутив WSL в Core редакции Windows Server или вам нужно установить WSL на Изолированном от интернета компьютере (оффлайн), вы можете скачать дистрибутив Ubuntu с помощью PowerShell командлета Invoke-WebRequest:

Invoke-WebRequest https://aka.ms/wslubuntu2204 -OutFile ubuntu-2204.appx –UseBasicParsing

Установите пакет для WSL с помощью:

Add-AppxPackage .\ubuntu-2204.appx

После окончания установки появится окно, в котором вам будет предложено указать имя пользователя и пароль для вашего дистрибутива.

задать пароль для wsl

После установки вы можете в меню Пуск появится отдельная программа для запуска Linux.

Также вы можете запустить ваш Linux из отдельной вкладки Windows Terminal или с помощью команды
wsl
.

Команды для управления WSL в Windows

Рассмотрим основные команды для управления ядром и дистрибутивами Linux в WSL.

Проверить текущую версию ядра WSL:

wsl --version

версия wsl в windows

Обновить ядро WSL вручную:

wsl --update

Откатится к предыдущему ядру WSL:

wsl --update rollback

Вывести список установленных версий Linux:

wsl --list

Вывести дистрибутив Linux, который используется по-умолчанию:

wsl --status

Дистрибутив Linux по-умолчанию в WSL можно изменить:

wsl --setdefault Ubuntu

Запустить определенный дистрибутив в WSL:

wsl -d kali-linux

Завершить среду WSL:

wsl --shutdown

Можно войти в WSL Ubuntu под root и сбросить пароль:
ubuntu config --default-user root
Passwd

Вернуть пользователя по умолчанию
ubuntu config --default-user your_username

Для настройки параметров WSL и дистрибутивов Linux используются конфиг файлы:

  • wsl.conf – файл с настройками конкретного дистрибутива Linux (находится в директории /etc)
  • .wslconfig – глобальные настройки WSL, которые применяются ко всем дистрибутовам (находится в профиле пользователя в
    %UserProfile%
    )

Например, если вы хотите ограничить использование оперативной памяти и CPU компьютера дистрибутивами Linux в WSL, создайте такой файл
%UserProfile%\.wslconfig
:

[wsl2]
memory=2GB
processors=2

Использование Linux в среде WSL

Дистрибутив Linux, установленный в WSL является полноценной операционной системой. Поэтому после установки рекомендуется выполнить обновление пакетов. Для Ubuntu выполните команду:

$ sudo apt-get update && sudo apt-get upgrade -y

обновление пакетов в ubuntu wsl

Файловая система вашего дистрибутива Linux хранится в профиле пользователя в виде VHDX файла. Например, виртуальный диск Ubuntu хранится в папке
%USERPROFILE%\AppData\Local\Packages\CanonicalGroupLimited.Ubuntu_79rhkp1fndgsc\LocalState

файл vhdx образа диска в linux wsl

Файловая система Linux в WSL монтируется в виде сетевой папки прямо в проводник Windows.

Также для прямого доступа к файлам WSL из Windows можно использовать UNC путь. Например:

notepad \\wsl$\Ubuntu\sysops\home\1122.txt

В свою очередь локальные диски Windows монтируются в WSL в папку mnt. Вывести список файлов папок на диске C:

wsl
ls /mnt
ls/mnt/c

просмот файлов на диске windows из wsl

Другие примеры запуска Linux команд из Windows:
dir | wsl grep Sa
wsl ls ‑la > 123.txt
wsl ls ‑la /proc/cpuinfo
wsl ls ‑la “/mnt/c/Program Files”

Вы можете установить любые пакеты в Linux. Например, установите файловый менеджер Midnight Commander:

$ sudo apt-get install mc

В современной версии WSL 2 вы можете запускать из Windows любые приложения Linux с графическим интерфейсом (X11 и Wayland). Например, установите графический редактор:

$ sudo apt install gimp -y

Чтобы запустить его из Windows просто выполните команду:

wsl gimp

How can I run Linux apps on Windows?

Yes, you heard it right! You can run Linux apps on Windows like native apps on the Windows system by following this tutorial.

With the release of Windows Subsystem for Linux (WSL), you can now run Linux applications directly on your Windows system, eliminating the need for dual-boot configurations or virtual machines. WSL2, in particular, integrates a full Linux kernel into Windows, allowing you to run Linux GUI applications as if they were native Windows applications. This guide will walk you through the process of configuring WSL, installing the required components, and running Linux GUI applications on Windows.

System Requirements: Windows 10 (Version 2004 and higher) or Windows 11, and a 64-bit processor with virtualization support enabled in BIOS/UEFI.

Step 1: Enable WSL and WSL2

  1. Open PowerShell as an administrator.
  2. Run the following command to enable the WSL feature:
dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart
Enabling WSL feature in Windows by executing the command: "dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart"

  1. Next, execute the following command to enable the Virtual Machine Platform, which is required for WSL2:
dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
Enabling Virtal Machine Platform feature for WSL

  1. Restart the machine to complete the changes.
  2. Then set WSL2 as the default version by running:
wsl --set-default-version 2
To set WSL2 as default version, execute command: wsl --set-default-version 2

Step 2: Install a Linux Environment

You can install various Linux distros, such as Ubuntu, Kali Linux, Debian, Fedora Remix, etc, directly from the Microsoft Store after setting up WSL. Additionally, other distributions like Manjaro and community-developed versions such as Arch Linux can also be installed through unofficial channels like GitHub.

Open the Microsoft Store and search for a Linux distribution, like Ubuntu or Kali Linux. Click Install and wait for the installation to complete. Once installed, launch the Linux environment from the Start menu.

Sometimes, you may encounter an issue like the screenshot below indicating that the WSL 2 requires an update to its kernel component. This often happens when the WSL 2 kernel is outdated or hasn’t been installed yet.

Error: 0x800701bc WSL 2 requires an update to its kernel component.

To solve this issue, update the WSL kernel by executing the following command in the PowerShell:

wsl.exe --update
Error: 0x800701bc WSL 2 requires an update to its kernel component. Solve this error with executing the command: wsl.exe --update in powershell.

Now go ahead with launching the Linux distro you installed from the Microsoft Store.

When you first launch the Linux environment, it will prompt you to create a username and password. Complete the setup by following the on-screen instructions.
Setting up Ubuntu in WSL.

Step 3: Running Linux GUI Applications

After setting up the Linux distribution, ensure that it is updated, and install the necessary GUI applications. For example, to run the Gedit application, which is exclusive to Linux distros, follow these steps:

  1. Update the Linux distribution using the appropriate update command for it:
sudo apt update && sudo apt upgrade
  1. Next, execute the installation command for the specific software you need. (For example: Gedit installation):
sudo apt install gedit
  1. After application installation, simply type the application name in the WSL terminal, and it will open as a window on your Windows desktop
gedit
Running Linux apps on Windows!

Step 4: Pinning Linux GUI Application to Windows

To pin a Linux GUI application like gedit to the Windows taskbar or create a desktop icon, follow these steps:

  1. Search for the application: Open the Windows search bar and type the name of the application (e.g., gedit).
  2. Pin to Taskbar: Once you find the application in the search results, right-click on it and select Pin to Taskbar.
Opening Linux apps from Windows taskbar.

  1. Create a Desktop Icon: If you prefer a desktop icon, right-click on the application and select Open File Location. This will open the application’s location in Windows File Explorer.
  2. From there, right-click the application, choose Send to, and then select Desktop (create shortcut).
Opening Linux apps from Windows Desktop.

This will allow users to easily pin the app to the taskbar or create a desktop shortcut for quick access.

Important Features to Explore

  1. Your Windows file system is accessible from within Linux distro at /mnt/c/
  2. Your Linux distro files can be accessed from your Windows system by typing \\wsl$ into the address bar of Windows File Explorer.
  3. You can drag files between Windows and Linux applications.
  4. You can write scripts that use both Windows and Linux tools to automate tasks.

With WSL2 and integrated GUI support, running Linux applications on Windows is now easier and more efficient than ever. Whether you need to test software, develop in a Linux environment, or simply use specific Linux tools, WSL2 offers a seamless experience that makes Linux apps feel like they’re a natural part of your Windows system.

Managed VPS Hosting, Simplified

Unlock the potential of your website with Veeble VPS. Experience powerful hosting without the hassle. Get started today!

Explore Plans

Although Windows users could also wish to run Linux software, Linux users frequently desire to run Windows applications on Linux. You can use Linux applications without leaving Windows, whether you’re searching for an improved development environment or strong command-line tools. There are several alternatives to purchasing a new laptop to run the OS for running Linux applications on Windows. Since anybody can set up a virtual machine with a free Linux distribution without the requirement for software licenses, it is simpler than running Windows software on Linux. 

There are two popular methods for running Linux software on Windows, they are

  • WSL (Windows Subsystem for Linux)
  • Virtual Machine

In this article, we’ll discuss how to implement both of these methods briefly.

Note: If you’re using Windows 11, the below steps can be omitted since Windows 11 can run Linux GUI apps out of the box.

Method 1: Windows Subsystem for Linux (WSL) 

The WSL is a feature available in Windows that’ll enable one to run the Linux file system, along with Linux command-line tools and GUI applications, directly on Windows. And they can be completely integrated with Windows tools. But the only drawback of WSL is that they are mainly targeted for command-line tools and cannot be used for graphics-intensive programs.

Step 1: Enable the Windows Subsystem for Linux optional feature

Start PowerShell or Command-Prompt with administrator privileges and enter the following command to enable the WSL services on windows, this may be enabled by default in some systems.

Enable-WindowsOptionalFeature -Online -FeatureName -Microsoft-Windows-Subsystem-Linux

 

Alternatively, you can enable it using the ‘programs and features’ settings.

 

Step 2:  Enable the Virtual Machine platform and Install WSL2 

The virtual machine has to be enabled before installing WSL, this can be done using the following command.

dism.exe /online /enable-feature /featurename:Microsoft-Windows-Subsystem-Linux /all /norestart

 

Once it has been enabled, install WSL by entering the following command in PowerShell or Command-Prompt.

wsl --install

Set the default version of WSL to 2

wsl --set-default-version 2

 

Step 3: Download and Install a Linux distribution

You can download and install any distro of your choice, for the sake of convenience we’ll be installing ubuntu. Navigate to Microsoft Store and search for ‘ubuntu’ then install the application. Once downloaded open the app and follow through with the installation wizard. Once the installation process is complete you’ll be left with the following terminal. Linux Command-line tools can be executed using this terminal.

 

Step 4: Download and Install VcXsrv Windows X Server

The X server is a third-party display manager which is a provider of graphics resources and keyboard/mouse events. Download VcXsrv Windows X Server from the link provided — VcXsrv Windows X Server

Once the setup is complete, make sure to disable the access control option to avoid running into errors while running the GUI applications.

 

Step 5: Setting up the DISPLAY environment variable 

Starting the bash terminal, we have to set the DISPLAY environment variable so it uses the windows host IP address since WSL2 and Windows host doesn’t share the network device. Use any of the following commands to set the DISPLAY variable.

export DISPLAY=$(ip route|awk ‘/^default/{print $3}’):0.0

export DISPLAY=»`grep nameserver /etc/resolv.conf | sed ‘s/nameserver //’`:0″

 

Run the below command to check whether the variable is properly set or not.

echo $DISPLAY

 

The variable is reset every time a session is restarted so as to avoid running the command each and every time we open the terminal. We can add the command at the end of the /etc/bash.bashrc file. Open the bashrc file using nano or vim and then add the command at the end.

sudo nano /etc/bash.bashrc

 

Step 6: Create a .xsession file in the user’s home directory

The following command can be used to create a .xsession file in the user’s home directory /home/<user>/.xsession with the content xfce4-session.

echo xfce4-session > ~/.xsession

Now Windows desktop can run Linux GUI apps.

 

Method 2: Using a Virtual Machine

Using a Virtual Machine is the most efficient and easy way to run Linux apps on Windows, we’ll briefly discuss the installation and setting up a virtual machine with a Linux OS.

Step 1: Download and Install a Virtual Machine 

Download a virtual machine of your choice (Oracle or VMware), here we’ll be using a VMware workstation. Download the software from the below link and follow the installation process. Refer to this How to Install VirtualBox on Windows GeeksforGeeks article for setting up a virtual machine using oracle.

Download VMware Workstation.

 

Step 2: Download a Linux distribution of your choice

You can download any Linux distribution, below are some of the most popular choices along with their links.

  • Ubuntu
  • Pop! OS
  • Linux Mint
  • Fedora

Step 3: Installing the OS

Open VMware Workstation, and click on the ‘Create new Virtual Machine’. And then select the installer disc image option and choose the downloaded Linux operating system’s ISO file. 

 

Specify the disk capacity and click on next.

 

Name the virtual machine and move on to the next step.

 

 Start the virtual machine to boot up the OS and follow the installation steps. Once the installation is complete you can run any Linux GUI apps using the virtual machine.

 

Step 4: Starting and Running the applications

You can now run any Linux application while within the virtual machines environment, here are some examples.

$ gedit

 
$ sudo apt install x11-apps -y
$ xcalc

 
$ xclock

 
$ xeyes

 

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Не удалось найти ip адрес сервера как решить проблему на компьютере windows 10
  • Windows map folder to folder
  • Windows 10 автоматически не обновляется рабочий стол windows
  • Что появилось раньше mac или windows
  • Сколько примерно переустанавливается windows 10