R subprocess failed when launched from windows task manager - windows

Setup & Config
Windows 10
[1] "R version 3.5.0 (2018-04-23)
A C:/test.r containing
library(subprocess)
is_windows <- function () (tolower(.Platform$OS.type) == "windows")
R_binary <- function () {
R_exe <- ifelse (is_windows(), "R.exe", "R")
return(file.path(R.home("bin"), R_exe))
}
handle <- spawn_process(R_binary(), c("--no-save"))
Sys.sleep(1)
print(handle)
process_write(handle, 'n <- 10\n')
process_write(handle, "rnorm(10)\n")
process_read(handle, PIPE_STDOUT, timeout = 1000)
Results
1 - Launching test.R in a Rgui.exe/Rterm.exe everything works
2 - Launching test.R through task scheduler I got the following error
Error in spawn_process(R_binary(), c("--no-save")) :
could not create process: Accès refusé ("Access refused")
Exécution arrêtée ("Excution stopped")
You can launch test.R by doing a manual task scheduler task or by
install.packages("taskscheduleR")
library(taskscheduleR)
myscript <- system.file("extdata", "helloworld.R", package = "taskscheduleR")
myscript="C:/test..r"
taskscheduler_create(taskname = "myfancyscript", rscript = myscript,
schedule = "ONCE", starttime = format(Sys.time() + 10*60, "%H:%M"))
taskcheduler_runnow("myfancyscript")
(Then you can read the error log in the subprocess directory)
Question ?
It seems that a R process launched by task scheduler has lower right and fail to launch a subprocess, why ?
I already tried to put the task scheduler process with the highest privilege but it failed !
Thanks

Related

Gradle Task - unable to execute fibonacci series in groovy

Facing problem in a question:
Write a gradle program to generate 10 fibonaci series, with task name as fibo, and variable name as num. Use command line argument for num.
For example, if a task name is test and I want to pass 10 as the input, use gradle test -Pnum=10.
I have created a function:
def fibo(n){
a = 0
b = 1
if (n == 1)
println a
else if
(n == 2)
println a + " " + b
else if (n > 2) {
print a + " " + b
i = 2
while (i <= n)
{
c = a + b
print " " + c
a = b
b = c
i = i + 1
}
}
}
My question is, how to link it with a task as I encounter error like:
FAILURE: Build failed with an exception.
* What went wrong:
Task 'fibo' not found in root project 'root'.
* Try:
Run gradle tasks to get a list of available tasks. Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED
Total time: 2.61 secs
or how to pass parameters in a gradle task?
Note: Please do not suggest optimization in fibonacci code, thats not a concern for now.
You can define a task like this:
def hello(name) {
println "Hello, $name"
}
task sayHello() {
doLast {
hello sayHelloTo
}
}
And call it like this:
% gradle sayHello -PsayHelloTo=World
> Task :sayHello
Hello, World
BUILD SUCCESSFUL in 518ms
1 actionable task: 1 executed
def fibo(num) {
if (num < 2) {
return 1
} else {
return fibo(num-2) + fib(num-1)
}
}
task (fibo) << {
println fibo(5)
}

How to get process path from PID when process launches?

In macOS X , I am monitoring all process launch event.
When process launches I am getting PID from kernel.
And using that PID I am retrieving full process Path in user mode.
I am using proc_pidpath() for process lauch event only. If I try to get process path of already running process it works .
#define MAX_PROCESS_PATH_LEN 1024
int iReturn;
char ProcessPath[MAX_PROCESS_PATH_LEN];
iReturn = proc_pidpath(processID , processPath , sizeof(ProcessPath));
if(0 == iReturn)
{
// proc_pidpath failed
}
else
{
NSLog(#"My Process Path = %s" , ProcessPath);
}
Input Task :
launch Chess.app from /Application/Chess.app
Actual Output :
My Process Path = /sbin/launchd
Expected output is /Application/Chess.app or /Applications/Chess.app/Contents/MacOS/Chess.
Can anyone please help me how to get process path when process is fork but may be not initialised ?

subprocess sometimes sends returns empty

I have the following class that is used to run a third party command line tool which I have no control over.
I run this ina Qthread in a PyQt Gui.
I turn the gui into an EXE using Pyinstaller
Problems are more prevalent when it is an EXE
class CLI_Interface:
def process_f(self, command, bsize=4096):
self.kill_process(CLI_TOOL)
startupinfo = STARTUPINFO()
startupinfo.dwFlags |= STARTF_USESHOWWINDOW
startupinfo.wShowWindow = SW_HIDE
p = Popen(command, stdout=PIPE, stderr=PIPE,
startupinfo=startupinfo, bufsize=bsize, universal_newlines=True)
try:
out, err = p.communicate(timeout=120)
except TimeoutExpired:
p.kill()
out, err = p.communicate()
return out.split(), err.split()
def kill_process(self, proc):
# Check process is running, Kill it if it is,
# return False if not.
# uses its own popen for Stderr >> stdout
# If we use the self.process_f method, it will create an infinite loop
startupinfo = STARTUPINFO()
startupinfo.dwFlags |= STARTF_USESHOWWINDOW
startupinfo.wShowWindow = SW_HIDE
try:
kill_proc = Popen("TaskKill /IM {} /T /F".format(proc), stdout=PIPE, stderr=STDOUT,
startupinfo=startupinfo, universal_newlines=True).communicate()[0]
if 'ERROR' not in kill_proc.split():
return True # Process Killed
else:
self.kill_process(proc)
except Exception as e:
return False
def download_data(self, code):
""" download data from the device based on a 5 digit code """
command = '"{}" -l {},{} {}'.format(CLI_TOOL_PATH,
code[0], code[2], code[1])
try:
p = self.process_f(command)
proc, err = p[0], p[1]
try:
if err[-2] == '-p':
return False
return True
except IndexError:
if not proc:
return False # This means there is no data but the file is still saved!!
pass
return True
except Exception as e:
return False
def ....
def ....
def ....
Thread:
class GetDataThread(QThread):
taskFinished = pyqtSignal()
notConnected = pyqtSignal()
def __init__(self, f, parent=None):
super(GetDataThread, self).__init__(parent)
self.f = f
def run(self):
is_dongle_connected()
DD = cli.download_data(self.f)
if not DD:
self.notConnected.emit()
else:
self.taskFinished.emit()
I either get a done! or error - This is normal when running from the command line.
Sometimes I get an empty list returned and I put this back into a recursive loop after killing the program.
However, it does not seem to restart properly and the problem continues - it gets stuck in a loop of nothing!.
Meanwhile, the csv files the cli tool produces are created as normal yet I have no data from stdout / stderr
Looking at processes the conhost and the cli tool are destroyed no problem.
The gui will continue to fail (until I unplug and plug in the dongle and / or restart the program / computer.
When I open the CLI and run the same command, it works fine or throws an error (which I catch in the program no problem)
I have tried setting a buffer as some files generated can reach 2.4mb
I tried setting a higher timeout to allow for it to finish.
There does not seem to be a correlation with file size though and it can get stuck at any size.
The flow is like so:
Gui >> CLI >> Dongle >> Sensor
Running on Windows 10
How can I make the connection more solid or debug what processes might still be lingering around and stopping this?
Is it blocking?
Is it a pipe buffer overflow? - If so How do I determine the correct bufsize?
Is it something to do with PyQt and Python Subprocess or Pyinstaller?
Would it be better to use QProcess instead of Subprocess?
Thanks in advance!

Can I tell LLDB to remove the active breakpoint?

When LLDB triggers breakpoint X, is there a command that will disable or remove X and then continue?
That's an interesting idea. There's no built in command to do this in lldb but it would be easy to implement as a user-defined command written in Python. SBThread::GetStopReason() will be eStopReasonBreakpoint if that thread stopped because of a breakpoint. SBThread::GetStopReasonDataCount() will return 2 -- indicating that the breakpoint id and location id are available. SBThread::GetStopReasonDataAtIndex(0) will give you the breakpoint ID, SBThread::GetStopReasonDataAtIndex(1) will give you the location ID. (a single user-specified breakpoint may resolve to multiple locations. e.g. an inlined function, or a function name that occurs in multiple libraries in a single program.)
Here's a quick & dirty example of a python command that does this. I put this in ~/lldb where I save my lldb user-defined commands and then in my ~/.lldbinit file I have a line like command script import ~/lldb/disthis.py.
In use, it looks like this:
% lldb a.out
(lldb) target create "a.out"
Current executable set to 'a.out' (x86_64).
(lldb) br s -n main
Breakpoint 1: where = a.out`main + 15 at a.c:4, address = 0x0000000100000f4f
(lldb) r
Process 67487 launched: '/private/tmp/a.out' (x86_64)
Process 67487 stopped
* thread #1: tid = 0x290c51, 0x0000000100000f4f a.out`main + 15 at a.c:4, queue = 'com.apple.main-thread', stop reason = breakpoint 1.1
#0: 0x0000000100000f4f a.out`main + 15 at a.c:4
1 #include <stdio.h>
2 int main()
3 {
-> 4 puts ("HI");
5 puts ("HI");
6 }
(lldb) com scr imp ~/lldb/disthis.py
(lldb) disthis
Breakpoint 1.1 disabled.
(lldb) br li
Current breakpoints:
1: name = 'main', locations = 1
1.1: where = a.out`main + 15 at a.c:4, address = 0x0000000100000f4f, unresolved, hit count = 1 Options: disabled
(lldb)
Pretty straightforward.
# import this into lldb with a command like
# command script import disthis.py
import lldb
def disthis(debugger, command, *args):
"""Usage: disthis
Disables the breakpoint the currently selected thread is stopped at."""
target = None
thread = None
if len(args) == 2:
# Old lldb invocation style
result = args[0]
if debugger and debugger.GetSelectedTarget() and debugger.GetSelectedTarget().GetProcess():
target = debugger.GetSelectedTarget()
process = target.GetProcess()
thread = process.GetSelectedThread()
elif len(args) == 3:
# New (2015 & later) lldb invocation style where we're given the execution context
exe_ctx = args[0]
result = args[1]
target = exe_ctx.GetTarget()
thread = exe_ctx.GetThread()
else:
print "Unknown python function invocation from lldb."
return
if thread == None:
print >>result, "error: process is not paused, or has not been started yet."
result.SetStatus (lldb.eReturnStatusFailed)
return
if thread.GetStopReason() != lldb.eStopReasonBreakpoint:
print >>result, "error: not stopped at a breakpoint."
result.SetStatus (lldb.eReturnStatusFailed)
return
if thread.GetStopReasonDataCount() != 2:
print >>result, "error: Unexpected number of StopReasonData returned, expected 2, got %d" % thread.GetStopReasonDataCount()
result.SetStatus (lldb.eReturnStatusFailed)
return
break_num = thread.GetStopReasonDataAtIndex(0)
location_num = thread.GetStopReasonDataAtIndex(1)
if break_num == 0 or location_num == 0:
print >>result, "error: Got invalid breakpoint number or location number"
result.SetStatus (lldb.eReturnStatusFailed)
return
bkpt = target.FindBreakpointByID (break_num)
if location_num > bkpt.GetNumLocations():
print >>result, "error: Invalid location number"
result.SetStatus (lldb.eReturnStatusFailed)
return
bkpt_loc = bkpt.GetLocationAtIndex(location_num - 1)
if bkpt_loc.IsValid() != True:
print >>result, "error: Got invalid BreakpointLocation"
result.SetStatus (lldb.eReturnStatusFailed)
return
bkpt_loc.SetEnabled(False)
print >>result, "Breakpoint %d.%d disabled." % (break_num, location_num)
return
def __lldb_init_module (debugger, dict):
debugger.HandleCommand('command script add -f %s.disthis disthis' % __name__)

From bash script how to tell when & process finishes

I am attempting to kick off multiple commands in a bash script but wait for them to complete
It looks something like this:
A &
B &
C &
D
Unfortunately i don't know which of these processes will finish first. But i need the whole script to complete when finished with all processes.
So like a rookie i tried:
(A &
B &
C &
D) && E
Unfortunately E only execs after D completes. I would like it if i could get E to happen after A - D exec
Hopefully that sums the problem.
Thanks
A &
B &
C &
D &
wait
E
From the help listing:
wait: wait [-n] [id ...]
Wait for job completion and return exit status.
Waits for each process identified by an ID, which may be a process ID or a
job specification, and reports its termination status. If ID is not
given, waits for all currently active child processes, and the return
status is zero. If ID is a a job specification, waits for all processes
in that job's pipeline.
If the -n option is supplied, waits for the next job to terminate and
returns its exit status.
Exit Status:
Returns the status of the last ID; fails if ID is invalid or an invalid
option is given.
wait(1) is the canonical solution, but I've used a q&d solution in the past:
( A & B & C & D & ) | cat; E

Resources