Open linux program on windows

Запуск программ Linux в Windows Running Linux programs on Windows

Для запуска программы Linux в Windows возможны следующие варианты: To run a Linux program on Windows, you have these options:

  • Запуск программы «как есть» в подсистеме Windows для Linux (WSL). Run the program as-is on the Windows Subsystem for Linux (WSL). В WSL программа выполняется непосредственно на оборудовании компьютера, а не на виртуальной машине. In WSL your program executes directly on the machine hardware, not in a virtual machine. WSL также поддерживает прямые вызовы файловой системы между системами Windows и Linux, устраняя необходимость в SSL-транспорте. WSL also enables direct filesystem calls between Windows and Linux systems, removing the need for SSL transport. WSL разработана как среда командной строки и не рекомендуется для приложений, интенсивно использующих графику. WSL is designed as a command-line environment and is not recommended for graphics-intensive applications. Дополнительные сведения см. в документации по подсистеме Windows для Linux. For more information, see Windows Subsystem for Linux Documentation.
  • Запуск программы «как есть» на виртуальной машине Linux или в контейнере Docker на локальном компьютере или в Azure. Run the program as-is in a Linux virtual machine or Docker container, either on your local machine or on Azure. Дополнительные сведения см. в разделах Виртуальные машины и Docker в Azure. For more information, see Virtual Machines and Docker on Azure.
  • Компиляция программы с использованием gcc или clang в средах MinGW или MinGW-w64, которые предоставляют слой преобразования системных вызовов Linux в системные вызовы Windows. Compile the program using gcc or clang in the MinGW or MinGW-w64 environments, which provide a translation layer from Linux to Windows system calls.
  • Компиляция и запуск программы с использованием gcc или clang в среде Cygwin, которая предоставляет более полную среду Linux в Windows по сравнению с MinGW или MinGW-w64. Compile and run the program using gcc or clang in the Cygwin environment, which provides a more complete Linux environment on Windows compared to MinGW or MinGW-w64.
  • Ручное портирование кода из Linux и компиляция для Windows с использованием Microsoft C++ (MSVC). Manually port your code from Linux and compile for Windows using Microsoft C++ (MSVC). Этот подход подразумевает рефакторинг кода, не зависящего от платформы, в отдельные библиотеки, и последующее переписывание специализированного кода, относящегося к Linux, в код для Windows (например, для API-интерфейсов Win32 или DirectX). This involves refactoring platform-independent code into separate libraries, and then re-writing the Linux-specific code to use Windows-specific code (for example, Win32 or DirectX APIs). Предположительно, этот вариант лучше всего подходит для приложений, в которых требуется высокопроизводительная графика. For applications that require high performance graphics, this is probably the best option.

—>

How to Run Linux on Windows 10

Linux users celebrated when it was reported that Bash shell was coming to Windows. And while it was not readily available to all users at first, the Windows 10 Creators Update made Linux on Windows more accessible.

Want to join in on the fun? Here’s how you can have Linux on Windows operating system without having to go through a virtual machine.

Defining Bash

Bash is basically a subsystem for Ubuntu. With Bash, you have a Linux system running inside Windows. It’s the very same Bash you’d find in Linux. You can use it to execute Linux commands without the need for a virtual machine or dual booting.

Читайте также:  Атол usb драйвер для windows 10 64 bit с цифровой подписью

Using Bash shell, developers can experience Linux natively on a Windows machine.

Enabling Linux on Windows

There are two ways of enabling a Windows subsystem for Linux. One is through PowerShell and the other would be through Windows Features.

Use PowerShell

Search for PowerShell and run it as an administrator. Once open, type this command and press Enter after:

You will be prompted to confirm by hitting Y or N. Press Y to proceed then reboot your computer. If it’s already installed, you won’t have to restart.

Use Windows Features

Use Search to look for a Control Panel application called Turn Windows Features On or Off.

Note: You can also get to the application by heading directly to Control Panel > Programs > Programs and Features > Turn Windows Features On or Off.

Once open, go through the list of features until you find Windows Subsystem for Linux. Tick the box to enable the option.

The computer will run and apply some changes. After it’s done, you will be asked to restart your computer.

Downloading a Linux Distro

Windows should now be able to run Linux. Now you have to download a Linux distro like Ubuntu for Windows to enter Linux commands.

Simply head on over to the Microsoft Store and download the Linux distro of your choice. You need to be logged in to proceed.

There are multiple systems available, but we’ll install Ubuntu and use it throughout the rest of this post. The download will likely take a while because of the large file size.

Running Linux

The Linux system you installed will run like a regular Windows application. Open Ubuntu. It will perform a one-time installation. You will be able to use Ubuntu Linux faster the next time you open the application.

Once installed, you will be asked to enter a username and a password. Provide all the necessary information.

From here on out, you will be able to go through the directory as you would in Linux. You will need to use SUDO APT to run root commands. You can also use APT-GET, APT INSTALL, AND APT UPDATE. You’re pretty much free to do everything you can do in a Linux terminal.

One thing to remember is that the Windows files system will be located inside the MNT folder.

If you want to edit Windows files from the Linux system, you would have to enter CD MNT, do LS then enter CD C and another LS to locate all the files stored inside Windows. Enjoy Linux with Windows 10!

Christopher Jan Benitez is a freelance writer for hire who provides actionable and useful web content to small businesses and startups. In his spare time, he religiously watches professional wrestling and finds solace in listening to ’80s speed metal. Read Christopher’s Full Bio

Как выполнять Linux-команды внутри Windows: официальный и сторонние способы

Под GNU/Linux-дистрибутивы создано огромное количество полезных и удобных инструментов и приложений для обычных пользователей и разработчиков. Далеко не всё из этого доступно на Windows, но, к счастью, для ОС от Microsoft есть решения, исправляющие эту проблему.

Содержание

WSL — официальная подсистема Linux внутри Windows

В Windows 10 существует крайне полезная вещь под названием Windows Subsystem for Linux (WSL). Она позволяет использовать GNU/Linux-среду прямо в Windows и запускать не только команды, но и, например, Bash-скрипты. Для использования WSL необходимо следовать инструкции ниже.

Шаг 1. Проверьте, подходит ли текущая версия Windows требованиям. Для этого нажмите сочетание клавиш Win+R, затем введите winver. Найдите строку «Сборка ОС» — она должна быть свежее версии 14316.

Шаг 2. Запустите стандартную утилиту PowerShell от имени администратора и введите в ней команду для включения WSL:

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

Шаг 3. Если версия Windows, определённая в первом пункте, свежее 18362, вы можете установить WSL 2, который в разы быстрее первой версии и обладает доработанным ядром. Введите команду ниже, если нужно установить WSL 2:

dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart

После этого скачайте и установите пакет обновления с официального сайта.

Читайте также:  Linux unzip from pipe

Шаг 4. Перезагрузите компьютер. Если была произведена установка WSL 2, введите в PowerShell от имени администратора следующую команду:

Шаг 5. После перезагрузки откройте фирменный магазин приложений Microsoft Store и найдите подходящий GNU/Linux-дистрибутив. Самым популярным является Ubuntu — вы можете установить любую версию из представленных в Microsoft Store.

Шаг 6. Как только установка завершится, найдите дистрибутив в меню «Пуск» и запустите его.

Шаг 7. Пройдите этап первоначальной настройки, введя имя нового пользователя и придумав пароль.

Шаг 8. Теперь различные GNU/Linux-команды можно выполнять, запустив дистрибутив, либо введя в командной строке wsl . Например, для просмотра всех файлов в текущей директории достаточно в командной строке выполнить wsl ls -a.

Обращу внимание на то, что путь к дискам в WSL отличается от такового в Windows. Вместо привычного C:/ используйте /mnt/c/. Также не забывайте про экранирование пробелов с помощью символа \ — это также пригодится при вводе путей к файлам.

Помимо выполнения базовых команд, с помощью WSL можно даже запускать приложения с графическим интерфейсом. Правда, рассчитывать на большое количество поддерживаемых подобных программ не стоит.

Шаг 1. Загрузите X-сервер и установите его.

Шаг 2. Запустите его с помощью ярлыка на рабочем столе. В открывшемся окне выберите вариант Multiple windows, затем Start no client. Завершите настройку кнопкой Finish.

Шаг 3. Откройте дистрибутив через меню Пуск и выполните команду export DISPLAY=:0

Шаг 4. Запустив приложение с графическим интерфейсом в WSL, вы увидите новое окно прямо в Windows.

CoreUtils — лёгкий инструмент для запуска базовых команд

Плюс данной утилиты — возможность запуска не только на Windows 10, но и на более старых версиях ОС. Кроме того, она легка и не занимает много места. Не обошлось без недостатков — программа скудна на функционал и не обновлялась очень давно. Она не только не умеет запускать скрипты и приложения с GUI, но и поддерживает лишь самые базовые GNU/Linux-команды. Установка CoreUtils весьма проста.

Шаг 1. Скачайте утилиту с официального сайта.

Шаг 2. Следуйте инструкциям установщика.

Шаг 3. Откройте «Панель управления», в разделе «Система и безопасность» выберите пункт «Система». На панели слева откройте «Дополнительные параметры системы». Нажмите кнопку «Переменные среды» и в открывшемся окне найдите область с заголовком «Системные переменные». В случае, когда там есть переменная Path, выберите её, нажмите «Изменить» и далее создайте новую строку. Содержимым этой строки должен быть путь к папке, который был указан при установке. Если вы ничего не меняли, то введите следующее:

Переменной Path нет? Тогда для начала создайте её кнопкой «Создать», затем в поле имени введите Path, а в поле значения — строку выше.

Шаг 4. Запустите командную строку и выполняйте команды прямо там.

Cygwin — запуск команд и Bash-скриптов

Ещё одна утилита, схожая с CoreUtils, но обладающая более широким функционалом — в том числе и возможностью запуска скриптов. Из минусов — немалый вес и более сложная установка. Разумеется, не идёт ни в какое сравнение с максимально удобным WSL, но для базовых команд вполне подойдёт.

Шаг 1. Загрузите Cygwin и запустите установку.

Шаг 2. Выберите Install from Internet, укажите директории для установки и загрузки пакетов, а также любой подходящий сайт из списка для скачивания файлов.

Шаг 3. В процессе установки можете выбрать необходимые пакеты, либо сразу нажать «Далее», оставив базовый набор.

Шаг 4. Откройте «Панель управления», в разделе «Система и безопасность» выберите пункт «Система». На панели слева откройте «Дополнительные параметры системы». Нажмите кнопку «Переменные среды» и в открывшемся окне найдите область с заголовком «Системные переменные». В случае, когда там есть переменная Path, выберите её, нажмите «Изменить» и далее создайте новую строку. Содержимым этой строки должен быть путь к папке, который был указан при установке. Если вы ничего не меняли, то введите следующее:

Читайте также:  Windows forward port netsh

Переменной Path нет? Тогда для начала создайте её кнопкой «Создать», затем в поле имени введите Path, а в поле значения — строку выше.

Шаг 5. Команды можно выполнять как через командную строку, так и через специальный терминал.

Шаг 6. Для удаления Cygwin достаточно удалить папку, в которую программа была установлена, а также (по желанию) значение из переменной Path по методу, обратному тому, что был описан в 4 шаге (не удаляйте саму переменную).

Run C program written in Linux on Windows

I have C program which I wrote in Linux that runs very well. Now I want to run it on Windows.

How do I easily run it on Windows?

4 Answers 4

Elaborating a bit on the answers from caf and jartieda.

Cygwin is an attempt to emulate a (nearly) complete POSIX execution environment in a native Windows process. It is complete enough that a surprising amount of Unix application code simply compiles and runs using the familiar ./configure && make && make install idiom. This trick was done by supplying a DLL that emulates POSIX system calls using the Windows API. Based on that, you get a complete GCC toolchain, bash, and all the usual command line utilities you are used to. One downside is that the compiled program is dependent on the Cygwin DLL, which makes it tricky to deliver the result to a system that does not already have Cygwin installed and whose user doesn’t want to use a Unix shell.

MinGW is a port of the GCC toolchain that generates native Windows applications that depend on the well known (and distributed with Windows itself) MSVCRT.DLL C runtime library. It makes no attempt to emulate a POSIX operating system, but applications that are mostly based on the standard C libraries, will often build essentially unchanged.

MSYS is a compile-time environment that provides enough Unix utilities (including bash) to often allow ./configure to run, and if the project supports the results, finish the build with MinGW’s GCC. The result is a native Windows executable that does not depend on any DLLs you don’t deliberately use aside from MSVCRT.DLL. Although the MSYS environment itself was a fork of an early version of the Cygwin project, it is primarily intended to be used to provide a unix-like place to compile native Windows applications: one would generally not build new applications based on its runtime environment.

Another approach to compiling for Windows is to use the MinGW cross compiler on linux. A number of MinGW’s core developers work that way, testing they product either under Wine, or under Windows running in a VM or a separate PC.

If the program has a GUI component, then you may have additional difficulties. Some GUI frameworks are available for both Linux and Windows. Qt, wxWidgets, and IUP all leap to mind, but there are others out there.

Edit: I’ve improved the paragraph above about MSYS to emphasize that it is intended to be a compile-time environment for building programs that run as native Windows applications, and not a full POSIX environment like Cygwin.

Note, also, that there is always the option of porting the project to one of the more traditional compilers for Windows development. Open Watcom, the Borland compilers, and Microsoft all have free or inexpensive versions, although often enough not under licenses that make the opens source community entirely happy.

This approach probably requires more effort because the differences between a Linux environment and the Windows environment become more visible when you also switch from one toolchain to another. This is especially true of the Microsoft compilers which are historically not as fully standards compliant as GCC.

Оцените статью