Execute an external executable within the same process space in C++ - c++

I'm trying to find an easy way to execute a java vm in windows using a C++ wrapper. I can use CreateProcess() to launch java.exe directly with all of my parameters that I need to give it. The problem is this now shows up as two processes in process manager. So, if I kill the parent process, the java.exe instance still sticks around.
The reason I need to do this is that we have a few java programs, all of which will be running concurrently. I want to be able to give them distinguishable names in the process explorer, so that if a user has trouble with one of them, they don't have to guess which java.exe process that corresponds to.

You can replace java.exe with your own executable. This article from the Java Glossary discusses how java.exe works and where to find the source for it. It's possible that you could get by simply by copying and then renaming java.exe

Related

Redirect stdout from Executable Custom Action to MSI log

I have a Custom Action that runs an executable within an msi installer package. The exe is compiled as a console application and stdouts necessary info.
I want that output redirected to the MSI log file.
I don't want the console to be shown during the installation.
For number 2 I suppose I can use windows as a subsystem, which will not open a console at all. But no output will be shown even if I run the exe from a terminal (PowerShell/CMD).
For number 1 I thought of running an executable as a subprocess called within a Custom Action DLL, but it is not possible since the exe is stored in a binary table and won't be generated when I need it. Moreover, it will have a random name.
The Custom Action's logic MUST be run as a separate process.
EDIT: Some colleagues wrote a free guide on installation testing. Maybe it will be useful in the future, to avoid such costly mistakes.
I don't think you can do it if you want to run the custom action as a separate process. I might be wrong. But I never tried this and it doesn't seem/sound possible.
Basically, the MSIEXEC process will own the handle of the log file created by the installation and I don't think you can share it with a separate process.
Why do you need to use a separate custom action process?
As a test - you could try to create an additional DLL custom action, that runs asynchronously. The purpose of this custom action is simply to communicate with your EXE process and write inside the log file any information you want to pass from the EXE custom action. I never tried this approach, but if you have time to kill and really need the main logic to remain in the EXE custom action, you could give it a try.

How to return a command from a c++ application to parent terminal?

Is it possible to run a c++ application from a terminal and on certain conditions return a command back into the terminal from which it was called from? For instance, if I were to run an application within my terminal and after my selections; my application needs to change my PATH by running an export command such as:
(USING BASH)
export PATH=.:/home/User/application/bin:$PATH
After I'm done and before my application completely closes can I make the application change my terminals local environment variables with the above command? Does Qt offer a way of doing this? Thanks in advance for any help!
No, you cannot change parent application environment.
Why? When your parent app started yours (probably using system()), it actually fork()ed - child process was born as to be almost exact replica of parent, and then that child used execve() call, which completely replaced executable image of that process with executable image of your application (for scripts it would be image of interpreter like bash).
In addition to that, that process also prepared few more things. One is list of open files, starting with file handles 0,1,2 (stdin, stdout, stderr). Also, it created memory block (which belongs to child process address space) which contains environment variables (as key=value pairs).
Because environment block belongs to your process, you can change your own environment as you please. But, it is impossible for your process to change environment memory block of parent (or any other process for that matter). The only way to possibly achieve this would be to use IPC (inter-process communication) and gently ask parent to do this task inside of it, but parent must be actively listening (on local or network socket) and be willing to fulfill such request from somebody, and child is not any special compared to any other process in that regard.
This also reason why you can change environment in bash using some shell script, but ONLY using source or . bash macro - because it is processed by bash itself, without starting any external process.
However, you cannot change environment by executing any other program or script for reasons stated above.
The common solution is to have your application print the result to standard output, then have the invoker pass it to its environment. A textbook example is ssh-agent which prints an environment variable assigment; you usually invoke it with eval $(ssh-agent)

Ways to communicate between JScript and Windows service

I have a Windows local service that may spawn off a process to execute a JScript script (in a .js file) via the Windows Script Host. The issue is that I need to notify my service of the results generated by the script in the .js file. A transfer or a simple 32-bit integer, or a string would suffice. What would be the way to do this?
PS. The code must run on Windows XP SP3 or later OS.
Your best bet is to create an out of process COM object that executes within your service. Just implement the necessary scripting interfaces and provide a member function to match the notification and call it from your script as such:
newObj = new ActiveXObject("localserver.mynotify");
newObj.Notify("finished");
Would the exit code of the process be enough?
Windows Scripting host has has a .Quit(errorCode) method that allows you to set the exit code.
You should be able to call WSH directly from the service and get the return code with GetProcessExitCode() by passing the process handle that you received after spawning it.
Note that almost everything you can do from a JScript file can also be done with native code.
Do you have to execute the .js file as an external process? Windows Scripting has COM objects that an app can use to run scripts within its own process. I use this to execute script files within my service processes, and it works fine. The hosting process can even implement its own IDispatch-based classes and pass them to the scripting engine to expose to scripts as global objects so the scripts can communicate with the hosting process without having to use new ActiveXObject or CreateObject() to access those objects.
I see your script is written in JScript and your app in C++.
Perhaps the easiest way to accomplish what you want is by writing a file, say, to programdata folder which your service should have access to. Maybe use a GUID for the particular request, pass that to the JScript so it's guaranteed to be a unique file. Not ideal.
Another way to get JScript output ... Can you call out to managed code (C#)? If so, you could use a .NET-based or .NET-callable JavaScript compiler/interpreter. This would allow you to avoid IActiveScript and also to grab the values right out of the script context or from function return. I've used Jurassic and JavaScriptDotNet, both very easy to use and extend.
This might open a problem if you heavily rely on ActiveXObject calls (ie: FileSystemObject) and don't want to write components. JuraScript wraps the Jurassic engine and add ActiveXObject support to it for COM automation.
I am a C++ newb, so I don't know how much of a leap this is for you although I know it's possible to interop between managed/C++.
Just thought I'd mention these scenarios as I didn't see them listed in answers.

C++, linux: how to limit function access to file system?

Our app is ran from SU or normal user. We have a library we have connected to our project. In that library there is a function we want to call. We have a folder called notRestricted in the directory where we run application from. We have created a new thread. We want to limit access of the thread to file system. What we want to do is simple - call that function but limit its access to write only to that folder (we prefer to let it read from anywhere app can read from).
Update:
So I see that there is no way to disable only one thread from all FS but one folder...
I read your propositions dear SO users and posted some kind of analog to this question here so in there thay gave us a link to sandbox with not a bad api, but I do not really know if it would work on anething but GentOS (but any way such script looks quite intresting in case of using Boost.Process command line to run it and than run desired ex-thread (which migrated to seprate application=)).
There isn't really any way you can prevent a single thread, because its in the same process space as you are, except for hacking methods like function hooking to detect any kind of file system access.
Perhaps you might like to rethink how you're implementing your application - having native untrusted code run as su isn't exactly a good idea. Perhaps use another process and communicate via. RPC, or use a interpreted language that you can check against at run time.
In my opinion, the best strategy would be:
Don't run this code in a different thread, but run it in a different process.
When you create this process (after the fork but before any call to execve), use chroot to change the root of the filesystem.
This will give you some good isolation... However doing so will make your code require root... Don't run the child process as root since root can trivially work around this.
Inject a replacement for open(2) that checks the arguments and returns -EACCES as appropriate.
This doesn't sound like the right thing to do. If you think about it, what you are trying to prevent is a problem well known to the computer games industry. The most common approach to deal with this problem is simply encoding or encrypting the data you don't want others to have access to, in such a way that only you know how to read/understand it.

How to interface with an executable in C++

I have an executable that I need to run some tests on in C++ - and the testing is going to take place on all of Windows, Linux and Mac OSes.
I was hoping for input on:
How would I interface with the previously built executable from my code? Is there some kind of command functionality that I can use? Also, since I think the commands change between OSes, I'd need some guidance in figuring out how I could structure for all three OSes.
EDIT - Interface = I need to be able to run the executable with a command line argument from my C++ code.
The executable when called from the commandline also ouputs some text onto a console - how would I be able to grab that ouput stream (I'd need to record those outputted values as part of my tests).
Feel free to ask me follow up questios.
Cheers!
If you use qt to develop your code, you'll find QProcess will allow you to spawn a command line program in a platform-agnostic way.
Essentially:
QObject *parent;
QString program = "yourcommandlineprogram";
QStringList arguments;
QProcess *myProcess = new QProcess(parent);
myProcess->start(program, arguments);
You can then read from the process with various function calls such as readAllStandardOutput (), and write to the input of the process with QProcess::write(QString).
Alternatively, if you prefer Boost to Qt, Boost.Process will also let you launch processes. I confess I don't like the syntax as much...
boost::process::command_line cl("yourcommandlineprogram");
cl.argument("someargument");
boost::process::launcher l;
l.set_stdout_behavior(bp::redirect_stream);
l.set_merge_out_err(true);
l.set_work_directory(dir);
boost::process::child c = l.start(cl);
You can then work with your subprocess 'c' by using stream operators << and >> to read and write.
All those OSes support some form of "subprocess" calling technique, where your tester creates a new child process and executes the code under test there. You get to not only pass a command line, but also have the opportunity to attach pipes to the child process' standard input and output streams.
Unfortunately, there is no standard C++ API to create child processes. You'll have to find the appropriate API for each OS. For example, in Windows you could use the CreateProcess function: MSDN: Creating Processes (Windows).
See also Stackoverflow: How do you spawn another process in C?
As I understand, you want to:
Spawn a new process with arguments not known at runtime.
Retrieve the information printed to stdout by the new process.
Libraries such as QProcess can spawn processes, however, I would recommend doing it by hand for both Windows and MacOS/Linux as using QProcess for this case is probably overkill.
For MacOS/Linux, here's what I would do:
Set up a pipe in the parent process. Set the read end of the pipe to a new file descriptor in the parent.
fork.
In newly created child process, set stdout (file descriptor #1) to the write end of the pipe.
execvp in the newly created child process and pass the target executable along with what arguments you want to give it.
From the parent process, wait for the child (optional).
From the parent process, read from the file descriptor you indicated in Step 1.
First of all, is it possible that you simply need to want to make your original code reusable? In that case you can build it as library and link it in your new application.
If you really want to communicate with another executable then you can need start it as a subprocess of the main application. I would recommend the Process class of the Poco C++ libraries.
Looks like a job for popen(), available on Linux, Windows, and OS X
Sounds like you are only planning to do functional testing at the executable level. That is not enough. If you plane to do thorough testing, you should also write unit tests. For that there is some excellent frameworks. My prefered one (by far) for C++ is BOOST::Testing.
If you control source code there is also common tricks for functional testing beside launching exe from an external process : embed functional tests. You just add an option to your program that execute tests. This is cool because tests are embedded in code and autocheck can easily be launched in any execution environment.
That means that in the test environment, as you call your program with some test dedicated arguments, nothing keeps you from going the full way and redirect the content of stdout and even check the tests results from within the program. It will make the whole testing much easier than calling from an external launcher, then analysing the results from than launcher.