After searching the web about a problem I have I found that answer.
in brief, I need to spawn a new process from an Android application, and run a simple C program.
I've created simple C program, like the next one:
int main()
{
printf("This is the message before sleep() function\n");
while(1){
Sleep(1000);
}
printf("This is the message after 1 second");
return 0;
}
Iv'e complied the C program with Cygwin with the next command (gcc myProgram.c -o myProgram).
Iv'e put that file in the assest folder and I copied it at the begining of the program to the internal device memory to the folder "data/data/packageName/files/myProgram".
Now I want to execute the program, and when I will check, adb shell -> ps I want to see two process with the same name, but I can't find it.
I am trying to run the program like this:
Runtime.getRuntime().exec("chmod 755
data/data/packageName/files/myProgram");
This is not working, I can't find two process, and I don't know if this is the right way.
What I'm doing wrong?
Thanks.
You need to deploy the binary to the file system, to a location which is not marked as non-executable (that's why /sdcard/ and other common places don't help). You need to choose the version of your executable that matches the platform (armeabi, or x86, or mips). You should make sure that the file you deployed has the eXecutable permission.
The easiest way to ensure all this is to copy the arm build of your binary to ${project_root}/libs/armeabi/lib_myProgram_.so, and same for other relevant ABIs. Now the APK builder will pack the binary(s), and the installer will unpack them (with eXecutable permissions) to /data/data/your.package.name.with.dots/lib/lib_myProgram_.so.
All this done, you simply call from Java (the following line can be called from Activity or Service, which have access to context):
Runtime.getRuntime().exec(getContext().getApplicationInfo().nativeLibraryDir + "lib_myProgram_.so");
Related
I'm currently programming a Python script that opens a file in an different directory that the user enters in an input box. Everything runs fine but the jar file I used for testing doesn't run or show up. I'm using the Shimeji-ee.jar in testing, and at one point its tray icon showed up but disappeared immediately.
I tried running it in command prompt(since calling the jar file using the script is similar to running a file in CMD) and discovered that it only runs as long as the CMD window is open. A few searches later, I've found a way to run files in CMD that keeps it running even after closing the CMD. I wrote it in my script, no errors, but the Shimeji nor its tray icon doesn't ever appear anymore.
I've added a line at the end of my script that is also told to be an efficient way of keeping the script running, but it doesn't work either(could be another mistake here):
while True:
keyboard.wait('q')
if keyboard.is_pressed:
sys.exit()
Here's the line of code in my script that does the calling:
subprocess.run(['D:', 'cd', PurePath(fileDirectory), 'START', '""', fileToExecute], cwd=os.getcwd(), shell=True)
The code I learnt that makes a file run in the background(similar to adding & in a Linux terminal):
START "" program
I've had thoughts that the jar file I'm using could be the problem, but I haven't found any answers for hours. Is there anything wrong with the code or am I missing something?
Update:
Code finally worked after the first answer but I received an error that seemed it read the file as a double forward slash like this:
# The network path was not found //
or
# The system could not find the file //
The solution I found was just removing the '""' part of the code, which makes the code look like this:
subprocess.run(['START', fileToExecute], cwd=PurePath(fileDirectory), shell=True)
The problem is that your code:
subprocess.run(['D:', 'cd', PurePath(fileDirectory), 'START', '""', fileToExecute], cwd=os.getcwd(), shell=True)
executes the command D: with the arguments cd somedirectory START "" fileToExecute, which changes the current drive of the shell to the D drive and then terminates.
You probably want to execute
subprocess.run(['START', '""', fileToExecute], cwd=PurePath(fileDirectory), shell=True)
So I created a game launcher that successfully downloads a Zip and extracts it. But then it tries opening the Jar file that was in the zip, and all that happens is the game pops up for about 2 seconds then closes. If I manually double click it it works fine, or if I run it through the command line, it works fine... Here are the two snippets of code I've tried using to get the Jar running. (Take note the jar does not return any errors on run):
Runtime rt =Runtime.getRuntime();
rt.exec("java -jar \""+appdata+"\\gamefiles\\Game.jar\"");
and...
Process proc = new ProcessBuilder("java.exe", "-jar", appdata+"/gamefiles/Game.jar").start();
int result = proc.waitFor();
System.out.println(result);
Any feedback is appreciated, thanks.
Since you are using a process builder, and you don't specify anything about the environment, is there a chance that your JAR file can't find needed elements (like JVM location or classpath) because it's not getting an environmental variable?
I have a somewhat strange issue. I have a java application that installs few services that run as Jars. Previously I used installed Java to run these Jars. There are four services and all will be instantiated from a single batch file with sequential call to each other. Something like this,
start %JAVA_HOME% commandtoruntjarfile
would work and all four services will run in the background and only one java.exe visible in process explorer. So I had another service installed as windows service which would start stop these services by calling the run bat or shutdown bat.
Now the customer requirement changed to using an internalized version of java. I extract java to a location, make our own environment variable name "ABC_HOME" and the required syntax in batch changes to
%ABC_HOME%\javaw commandtorunjarfile
When its run it works. but there is no stopping these. When I go to process explorer I see 4 java.exe running each for the four run commands in the batch file. If I stop the windows service all the four keep working. If I restart the windows service the number of java.exe in process explorer goes to eight and keeps going up until windows has had enough of it.
How do I get around it? I think the solution should be to have the one java process in process explorer but I cant seem to find any solution for that.
[EDIT]
The four sub services are actually XYNT processes. In the normal scenario it would be something like this
[Process1]
CommandLine = java -Xrs -DasService=yes -cp jarfiles
WorkingDir = c: bin scache
PauseStart = 1000
PauseEnd = 1000
UserInterface = No
Restart = Yes
For using java from a specific location the following change was needed
CommandLine = %JAVA_PATH%\bin\java.exe -Xrs -DasService=yes -cp jarfiles
but this wouldn't work as it would not accept the path variable in XYNT.ini file. so I called a batch file here and in that batch file I used the above code. So here is what the change looks like,
CommandLine = batchfile.bat
and in batchfile.bat
%JAVA_PATH%\bin\java.exe -Xrs -DasService=yes -cp jarfiles
Usually, every Java program run on your system has its own virtual machine running, which means: one java.exe/javaw.exe per instance of your program.
I can not tell why it "worked" from your point of view with java.exe like you described first, but the behaviour you described for javaw.exe (having 4 java processes in the process explorer) would be what I'd have expected.
For me the question is not why you're seeing 4 vs. 1 java processes, but how you can start/stop the "services". Killing the Java VM externally doesn't seem a very good solution. I'd consider building some IPC into the Java services that allow you to gracefully terminate the processes.
I made a small java app that copies a directory from a CD to the HD. I made the program using Windows Vista and it worked, but when i ran it in Windows 7, it fails.
The main problem is that a folder inside the Program Files folder needs to be created.
I used DestinationFolder.mkdirs(), but it fails creating it
This is the java code:
public void Install_App()
{
File srcFolder = new File(System.getProperty("user.dir") + "\\WINDOWS");
File destFolder = new File("C:\\Program Files\\test1\\test2\\");
if (srcFolder.exists())
{
try{
if(!destFolder.exists())
{
destFolder.mkdirs();
}
copyFolder(srcFolder,destFolder,1);
}catch(IOException e){
e.printStackTrace();
JOptionPane.showMessageDialog(null, e.toString());
error=true;
System.exit(0);
}
} else
{
JOptionPane.showMessageDialog(null, "Error. Source Directory doesn't exist.");
error=true;
};
}
... and then there is a copyfolder function that copies the files with inputstream and outputstream.
The problem is that the folder is never created. My login user is an administrator. And as i said, it worked in Vista.
Could you help me, please?
Thanks.
The thing is that i created this app in java to run it in Windows and Mac.
In Windows it should autorun with and autorun.inf like this:
[autorun]
OPEN=java_app.bat
then this bat will run this:
#echo off
start javaw -jar "java_app.jar"
EXIT
so how can i modify it to run it as administrator automatically?
The main idea of this java app is simplify the process of install & use an external application no matter which OS are you using. If I have to ask the user to run it as admin it will loose it's sense (of been simple of use).
I am guessing you are running your code as regular user.
Writing into Program Files directory as a regular-user is by default blocked by UAC under Windows 7. That's why your Java code fails to create directories.
Try running your Java code from a privileged shell. You can have one by Start > [type cmd] > [right-click on 'cmd.exe' and select "Run as administrator"]. Now, run your compiled code with java -jar or java -classpath from the administrator command prompt. It should work now.
Automating the UAC prompt:
You need to create a manifest file as described in detail at [1] and [2] to let Windows/UAC know that your program would need elevated privileges.
Also check this [3] utility called elevate that would spawn your program as child process while handling the UAC permission requests all being made from the parent (elevate) program itself.
[1] [http://msdn.microsoft.com/en-us/library/aa511445.aspx][2]
[2] [http://msdn.microsoft.com/en-us/library/bb756929.aspx][3]
[3] [http://www.wintellect.com/cs/blogs/jrobbins/archive/2007/03/27/elevate-a-process-at-the-command-line-in-vista.aspx][4]
This is all the permission problems. I have the same problem on my machine. Nothing is wrong with your java code. I tried to create folder using command line and got "Access Denied".
C:\Users\alexr>mkdir "C:\Program Files\mytest"
Access is denied.
So, the solution is whether to create folder in other location or run as administrator. As #Alex K. aready said, refer to this post to learn how to get such permissions.
Windows 7 Create Folder in "Program Files" failing in C# code even thought I have admin rights!
You do not have the proper privileges to create directories in Program Files. You must start the application with administrative privileges.
An important thing to learn is that when you are developing your applications you should never write them to save/modify data inside Program Files; instead they should either write to AppData our My Documents.
Modifying files in Program Files has been severely deprecated ever since Windows Vista, and even earlier than that. You should try and follow this rule from the start, or it means headaches to rewrite your entire application if you ever want to publish it online.
I am trying to run a perl command with Java runtime exec in linux/ubuntu/gnome. The command generates an pdf file, but it saves it in my home folder. Is there any way that the exec method can set an output path for the commands executed? Thanks in advance.
The exec method just runs the command on the operating system, so you'll want to change the command you're running with exec more than anything in "Java" per se.
There are a few possibilities:
Change the working directory of your java program. The .pdf is being saved in your working directory because this is where the program is being run.
Unfortunately it's not simple to change this value after the program has been launched. It is, however, trivial to change before the program starts; just change the working directory before starting the program.
Move the file to it's desired location after it's been created in your home directory.
Change the command so that it includes the target location. Your perl script may have an option that will enable you to save it's output to a certain location (usually -o or --output). Using this your program would change from:
Runtime.exec("perl someprogram");
to something like:
Runtime.exec("perl someprogram -o /path/to/some.file")
You might be able to use "output redirection", if there is no option to do this.
Try something like what's below as your argument:
Runtime.exec("perl someprogram > /path/to/some.file")
Unfortunately, without knowing more details of your situation I can't provide more concrete advice.
While each approach has benefits and drawbacks, it's probably best to just implement the one that you understand best; if you can't get one to work, try another.
A good, free online resource for learning is Introduction to Linux: A Hands On Guide.
Section 2.2 has details on cd which you can use for 1..
Section 3.3, section 3 teaches about the mv command, which will be useful in 2..
Section 5.1 is about I/O redirection. Knowing about "output redirection" and the > operator, are important for 4..
For 3., you'll have to consult the documentation of the perl program you're using.
You could modify the Perl script to accept an absolute path for the output.
You can trying setting the working directory using exec(java.lang.String[], java.lang.String[], java.io.File) where File is the directory the command is executed from.
If all else fails, you'll can always copy the generated file from the Home directory to your final location.