CreateProcess error = 5, access denied.
Bugs encountered using java runtime. Getruntime(). Exec()
Bugs encountered using java runtime. Getruntime(). Exec()
Today, when using a wkhtmltopdf tool, you need to use a Java method, * runtime. Getruntime() returns the runtime object of the current application, and the exec() method of the object instructs the Java virtual machine to create a child process, execute the specified executable program, and return the process object instance corresponding to the child process. Through process, you can control the execution of the sub process or obtain the information of the sub process* An introduction link to this function is attached: runtime. Getruntime(). Exec()
when an error code is reported, guess that the reason is that the folder cannot be accessed or the command cannot be called.
public class WKTest {
public static void main(String[] args) {
String cmd = "D:/programfiles/wkhtmltopdf/bin --quality 75 https://www.nowcoder.com D:\work\wk-images/3.png";
try{
Runtime.getRuntime().exec(cmd);
System.out.println("ok");
}catch(IOException e){
e.printStackTrace();
}
}
}
java.io.IOException: Cannot run program "D:/programfiles/wkhtmltopdf/bin": CreateProcess error=5,Denied to access.
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
at java.lang.Runtime.exec(Runtime.java:620)
at java.lang.Runtime.exec(Runtime.java:450)
at java.lang.Runtime.exec(Runtime.java:347)
at com.nowcoder.community.WKTest.main(WKTest.java:15)
Caused by: java.io.IOException: CreateProcess error=5, Denied to access.
In Java, runtime. Getruntime().Exec() implements calling the server command script to execute the required functions. In other words, this line of code cannot be operated on the folder. You must access the script in the folder. Here I mainly call an. EXE file, which is modified as follows:
public class WKTest {
public static void main(String[] args) {
String cmd = "D:/programfiles/wkhtmltopdf/bin/wkhtmltoimage.exe --quality 75 https://www.nowcoder.com D:\work\wk-images/3.png";
try{
Runtime.getRuntime().exec(cmd);
System.out.println("ok");
}catch(IOException e){
e.printStackTrace();
}
}
}
Normal test:
ok
Process finished with exit code 0
Read More:
What happened
Creating a new Project on IntelliJ IDEA, it show me only 3 files f_demo7.iml, f_demo7.ipr, f_demo.iws.
But if I run Flutter create f_demo7 on the command line, it creates the project normally.
I am using Windows 10, and a new Flutter installation using master branch, and also run flutter doctor.
C:UsersclaudDevelopmentflutter>where flutter
C:UsersclaudDevelopmentflutterbinflutter
C:UsersclaudDevelopmentflutterbinflutter.bat
Flutter Doctor result
Downloading android-arm-profile tools... 1.2s
Downloading android-arm-release tools... 1.1s
[√] Flutter (on Microsoft Windows [Version 10.0.14393], channel @u)
• Flutter at C:UsersclaudDevelopmentflutter
• Framework revision 2f590eccbc (6 hours ago), 2017-05-10 22:08:27 -0700
• Engine revision f2581c9bcc
• Tools Dart version 1.23.0-dev.11.11
[√] Android toolchain - develop for Android devices (Android SDK 25.0.3)
• Android SDK at C:UsersclaudAppDataLocalAndroidsdk
• Platform android-25, build-tools 25.0.3
• Java binary at: C:Program FilesAndroidAndroid Studiojrebinjava
• Java version: OpenJDK Runtime Environment (build 1.8.0_112-release-b06)
[√] Android Studio (version 2.3)
• Android Studio at C:Program FilesAndroidAndroid Studio
• Gradle version 3.2
• Java version: OpenJDK Runtime Environment (build 1.8.0_112-release-b06)
[√] IntelliJ IDEA Ultimate Edition (version 2016.2)
• Dart plugin version 162.2924
• Flutter plugin version 12.1
[√] Connected devices
• ONEPLUS A3003 • a7cd8cad • android-arm • Android 7.1.1 (API 25)
Version information
IntelliJ IDEA 2016.2.5
• Flutter plugin 12.1
• Dart plugin 162.2924
* Windows 10
Error getting Flutter sdk information.
Exception
Unable to start process to watch Flutter devices: Cannot run program «C:UsersclaudDevelopmentflutterbinflutter.bat» (in directory «C:UsersclaudDevelopmentflutter»): CreateProcess error=5, Access is denied
com.intellij.execution.process.ProcessNotCreatedException: Cannot run program "C:UsersclaudDevelopmentflutterbinflutter.bat" (in directory "C:UsersclaudDevelopmentflutter"): CreateProcess error=5, Access is denied
at com.intellij.execution.configurations.GeneralCommandLine.createProcess(GeneralCommandLine.java:358)
at com.intellij.execution.process.OSProcessHandler.<init>(OSProcessHandler.java:46)
at io.flutter.run.daemon.DeviceDaemon$Command.start(DeviceDaemon.java:159)
at io.flutter.run.daemon.DeviceService.chooseNextDaemon(DeviceService.java:187)
at io.flutter.utils.Refreshable.runInBackground(Refreshable.java:214)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.io.IOException: Cannot run program "C:UsersclaudDevelopmentflutterbinflutter.bat" (in directory "C:UsersclaudDevelopmentflutter"): CreateProcess error=5, Access is denied
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
at com.intellij.execution.configurations.GeneralCommandLine.startProcess(GeneralCommandLine.java:368)
at com.intellij.execution.configurations.GeneralCommandLine.createProcess(GeneralCommandLine.java:354)
... 11 more
Caused by: java.io.IOException: CreateProcess error=5, Access is denied
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.<init>(ProcessImpl.java:386)
at java.lang.ProcessImpl.start(ProcessImpl.java:137)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029)
... 13 more
- Remove From My Forums
-
Question
-
Hello,
I’ve got a windows service application that is trying to spawn a process to execute another console application. It works great on Windows XP, but is failing on Server 2003 and Vista with error code 5, «Access denied». I’m suspecting it has something to do with security. Unfortunately, I am not sure what I should do. Could someone please point me in the right direction?
Thanks!
This is the code:
STARTUPINFO si;
PROCESS_INFORMATION pi;ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
ZeroMemory(&pi, sizeof(pi));if (CreateProcess(NULL, // application name
(LPSTR)commandLine.str().c_str(), // command line
NULL, // process security attributes
NULL, // primary thread security attributes
FALSE, // inherit handles
0, // creation flags
NULL, // environment block
NULL, // full path to the current directory for the process
&si, // startup info
&pi)) // process information
{
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
else
{
int lastErrorCode = GetLastError();
LPVOID lpMsgBuf = NULL;
FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER,
NULL,
lastErrorCode,
0,
(LPSTR) &lpMsgBuf,
0,
NULL);// bla bla
}
posted 11 years ago
-
Number of slices to send:
Optional ‘thank-you’ note:
import java.io.PrintStream;
import java.util.*;
public class NewThread implements Runnable{
Thread t;
NewThread(){
t = new Thread(this, «Demo Thread»);
System.out.println(«child thread:» + t);
t.start();
}
long startTime = System.currentTimeMillis();
public void run(){
Runtime r = Runtime.getRuntime();
Process p = null;
String s = «C:\Users\x\Desktop\ java -jar helol.jar»;
try
{
p = r.exec(s);
p.waitFor();
}
catch (Exception e)
{
System.out.println(«Exception error:» + e.getMessage());
}
System.out.println(«Project1 returned:» + p.exitValue());
System.out.println(«child thread exiting «);
long endTime = System.currentTimeMillis();
System.out.println(«Total elapsed time in execution of given .exe file in milliseconds is :» + (endTime-startTime));
System.out.println(«Heap utilization Statistics in Bytes»);
System.out.println(«Used Memory:»+ (r.totalMemory() — r.freeMemory()));
System.out.println(«Free Memory:»+ r.freeMemory());
System.out.println(«Total Available Memory:» + r.totalMemory());
System.out.println(«Maximum Available Memory:» + r.maxMemory());
}
}
class ThreadDemo {
public static void main(String args[]){
new NewThread();
try {
for(int i=05;i>0;i—){
System.out.println(«Main Thread:» + i);
Thread.sleep(1000);
}
} catch (InterruptedException e){
System.out.println(«Main thread Interrupted»);
}
System.out.println(«Main thread exiting»);
}
}
please help me out ASAP… i am trying to execute a jar file through this program in eclipse but it’s showing an error — createprocess=5 access is denied and i tried to change the permissions of respective folders and directory but couldn’t work and i made changes in configuration file of eclipse i.e eclipse.ini but still i am facing prob.
Содержание
- Устраняем ошибку 5 при доступе к данным
- Способ 1: Запуск с привилегиями администратора
- Способ 2: Открытие доступа к каталогам
- Способ 3: «Командная строка»
- Способ 4: Устранение проблем с Виндовс
- Заключение
- Вопросы и ответы
В некоторых ситуациях пользователи операционной системы Виндовс 10 могут столкнуться с проблемой, когда попытка открыть файл, папку или программу приводит к появлению ошибки с кодом 5 и текстом «Отказано в доступе». Также она нередко возникает при попытке запуска или перезапуска служб. Далее мы расскажем о причинах появления этого сбоя и предложим методы его устранения.
Устраняем ошибку 5 при доступе к данным
В большинстве случаев источником ошибки являются проблемы с правами на чтение и запись данных в текущей пользовательской «учётке». Также подобное сообщение появляется при сбоях в ОС, повреждении её компонентов или записей реестра.
Способ 1: Запуск с привилегиями администратора
Если открытие исполняемого файла программы, игры либо инсталлятора приложения приводит к появлению рассматриваемой ошибки, следует попробовать запустить его от имени администратора.
- Убедитесь, что у текущей учётной записи нужные права есть. Если это не так, предоставьте или получите их.
Урок: Получение прав администратора на Windows 10
- Перейдите к проблемному файлу. Выделите его, нажмите правую кнопку мыши и выберите в меню пункт «Запуск от имени администратора».
- Появится всплывающее окно с запросом на разрешение, щёлкните в нём «Да».
Далее приложение или инсталлятор должны запуститься нормально.
Способ 2: Открытие доступа к каталогам
Вторая причина проблемы, которую мы сегодня рассматриваем – неполадки с правами доступа к отдельному каталогу или диску. Предоставление нужных прав покажем на примере системного диска.
Внимание! Процедура может нарушить работу компьютера, поэтому рекомендуем создать точку восстановления!
Урок: Точка восстановления в Windows 10
- Откройте «Этот компьютер», найдите в нём системный накопитель и кликните по нему ПКМ, затем выберите в меню пункт «Свойства».
- Откройте вкладку «Безопасность». Нажмите на кнопку «Изменить» под блоком «Группы и пользователи».
Далее кликните «Добавить».
- В следующем окне обратитесь к блоку «Введите имена…». Наберите на клавиатуре слово
Все
, после чего щёлкните «Проверить имена».
Если появилось окошко «Имя не найдено», попробуйте в графе «Введите имя объекта» вписать слово
All
либо имя текущей учётной записи, после чего воспользуйтесь кнопкой «ОК». - Вернувшись к утилите разрешений, убедитесь, что выделена добавленная на предыдущем шаге группа. Далее в разделе «Разрешения для группы…» отметьте все пункты в столбце «Разрешить».
- Далее последовательно щёлкните «Применить» и «ОК», после чего перезагрузите компьютер.
Предоставление прав на чтение и запись системного носителя одновременно устраняет ошибку 5 как для исполняемых файлов, так и для служб, однако данная процедура небезопасна для работоспособности системы.
Способ 3: «Командная строка»
Рассматриваемая проблема может касаться только той или иной службы Виндовс. В этом случае можно воспользоваться средством «Командная строка».
- Откройте «Поиск», в котором начните вводить запрос
командная строка
. Выделите найденное приложение и нажмите на ссылку «Запуск от имени администратора» в правой части окна. - Последовательно введите в интерфейсе следующие команды:
net localgroup Администраторы /add networkservice
net localgroup Администраторы /add localservice
Обратите внимание! Пользователям Windows 10 с английской локализацией системы необходимо вводить Administrators вместо Администраторы!
- Закрывайте окно программы и перезагружайте ПК или ноутбук.
Данный метод безопаснее предыдущего, но и применим только при отказе в доступе для служб.
Способ 4: Устранение проблем с Виндовс
Если применение всех вышеприведённых методов не принесло результата, скорее всего источником проблемы являются неполадки в самой ОС.
- Первым делом проверьте обновления – возможно, в одном из недавно установленных присутствуют баги. Если же, напротив, вы давно не обновляли систему, попробуйте загрузить актуальные апдейты.
Урок: Как установить и как удалить обновления Windows 10
- Проверьте параметры антивируса – возможно, в нём активен строгий режим контроля, который не разрешает манипуляции с данными. Также стоит попробовать временно отключить защитное ПО.
Урок: Как отключить антивирус
Если же вы по каким-то причинам вообще не пользуетесь защитой от вирусов, рекомендуем ознакомиться со статьей по борьбе с ними — возможно, ваш компьютер стал жертвой заражения.
Подробнее: Борьба с компьютерными вирусами
- Дополнительно следует проверить работоспособность системных составляющих в целом и реестра в частности.
Подробнее:
Проверка и восстановление системных файлов в Windows 10
Восстановление реестра в Windows 10
Описанные выше рекомендации должны помочь в устранении проблемы.
Заключение
Мы рассмотрели варианты решения проблемы, при которой в Виндовс 10 появляется ошибка с кодом 5 и текстом «Отказано в доступе». Как видим, возникает она по разным причинам, из-за чего нет универсального метода устранения.
Еще статьи по данной теме:
Помогла ли Вам статья?
Problem
While running an update on a users web mode desktop GUI using IBM Rational Synergy the
user receives an error «Warning: Cannot run program «attrib»:CreateProcess error=5,Access is denied.»
The user’s work area is not updated.
Symptom
The following error is displayed:
«Warning: Cannot run program «attrib»: CreateProcess error=5, Access is denied.»
Cause
The FDCC security policy is inhibiting the operation.
Environment
Synergy environments usually in secure locations.
Diagnosing The Problem
You should check with your systems team to determine if your company implements FDCC regulations:
—————————————————————————————————-
- The FDCC, requires that all Federal Agencies standardize the configuration of approximately 300 settings on each of their Microsoft Windows systems. The reason for this standardization is to strengthen Federal IT security by reducing opportunities for hackers to access and exploit government computer systems.
All Government-furnished Microsoft Windows-based computers (whether operated by Government or contractor staff) are affected by this mandate.
The FDCC will have a noticeable impact on the way many users use their computers; for example, certain web sites may no longer be accessible to all users or the installation of software by standard users may no longer be permitted. Password requirements will also be strengthened.
—————————————————————————————————-
Resolving The Problem
Refer to your systems team to have them make changes for the user’s machine/account of your Rational Synergy user to fix this. They should be able to compare these settings to other team members if others are not seeing the behavior.
As a work around you can add the user seeing the error as a local administrator to the system seeing the issue.
Once the local admin is added to the local system right click on the Synergy GUI icon and
«Run as Administrator» and it will allow operations to continue.
[{«Product»:{«code»:»SSC6Q5″,»label»:»Rational Synergy»},»Business Unit»:{«code»:»BU053″,»label»:»Cloud & Data Platform»},»Component»:»General Information»,»Platform»:[{«code»:»PF033″,»label»:»Windows»}],»Version»:»6.5;7.1;7.2″,»Edition»:»»,»Line of Business»:{«code»:»LOB45″,»label»:»Automation»}}]