I am trying to use Boost.Asio's object_handle to wait for input from the console:
int main()
{
using namespace boost::asio;
io_service io;
windows::object_handle in(io);
in.assign(::GetStdHandle(STD_INPUT_HANDLE));
in.wait();
io.run();
return 0;
}
This works if I run it from the terminal, but when I try to debug into it with Visual Studio it skips wait(). What's going on?
A windows console application can create it's own console, or it can attach to an existing console (e.g. the parent command shell). This is likely what creates the difference.
You can influence the console allocation usually with things like start cmd /c myprog vs. ``start /b cmd /c myprog`, or you can explicitly create you console
The MSDN article that has the backgrounds and APIs is here:
Creation of a Console
Related
I am trying to compile on mingw a program that prints to console using Windows.h functions. Why do I get no output?
C file:
#include <Windows.h>
int main() {
HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
WriteConsoleA(out, "hello", 5, NULL, NULL);
return 0;
}
To print to a console your application must be a console application in the first place. A Windows GUI application can
Make sure you linked the application using the -mconsole flag.
Also make sure that you are not running the application from somewhere where the output may disappear right away (like an IDE). Instead open a command prompt and run your .exe file from there to see the output. Or you could add some code to wait for a key in your code so you can see the output before the window closes automatically.
How do stop the console window from closing after there has been a error when running a .exe?
I am keeping the window open with _ <- getLine but this of course only works if the program runs up to that point.
If you are asking how to keep the console window opened when invoked from a short cut, try invoking the program with cmd.exe /k ...
See, for instance: How do you keep the console from closing after the program is done in C?
In linux you can use command & to run command on the background, the same will continue after the shell is offline. I was wondering is there something like that for windows…
I believe the command you are looking for is start /b *command*
For unix, nohup represents 'no hangup', which is slightly different than a background job (which would be *command* &. I believe that the above command should be similar to a background job for windows.
I'm assuming what you want to do is run a command without an interface (possibly automatically?). On windows there are a number of options for what you are looking for:
Best: write your program as a windows service. These will start when no one logs into the server. They let you select the user account (which can be different than your own) and they will restart if they fail. These run all the time so you can automate tasks at specific times or on a regular schedule from within them. For more information on how to write a windows service you can read a tutorial online such as (http://msdn.microsoft.com/en-us/library/zt39148a(v=vs.110).aspx).
Better: Start the command and hide the window. Assuming the command is a DOS command you can use a VB or C# script for this. See here for more information. An example is:
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run("C:\yourbatch.bat"), 0, True
You are still going to have to start the command manually or write a task to start the command. This is one of the biggest down falls of this strategy.
Worst: Start the command using the startup folder. This runs when a user logs into the computer
Hope that helps some!
Use the start command with the /b flag to run a command/application without opening a new window. For example, this runs dotnet run in the background:
start /b dotnet run
You can pass parameters to the command/application too. For example, I'm starting 3 instances of this C# project, with parameter values of x, y, and z:
To stop the program(s) running in the background: CTRL + BREAK
In my experience, this stops all of the background commands/programs you have started in that cmd instance.
According to the Microsoft docs:
CTRL+C handling is ignored unless the application enables CTRL+C processing. Use CTRL+BREAK to interrupt the application.
You should also take a look at the at command in Windows. It will launch a program at a certain time in the background which works in this case.
Another option is to use the nssm service manager software. This will wrap whatever command you are running as a windows service.
UPDATE:
nssm isn't very good. You should instead look at WinSW project. https://github.com/kohsuke/winsw
If you take 5 minutes to download visual studio and make a Console Application for this, your problem is solved.
using System;
using System.Linq;
using System.Diagnostics;
using System.IO;
namespace BgRunner
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Starting: " + String.Join(" ", args));
String arguments = String.Join(" ", args.Skip(1).ToArray());
String command = args[0];
Process p = new Process();
p.StartInfo = new ProcessStartInfo(command);
p.StartInfo.Arguments = arguments;
p.StartInfo.WorkingDirectory = Path.GetDirectoryName(command);
p.StartInfo.CreateNoWindow = true;
p.StartInfo.UseShellExecute = false;
p.Start();
}
}
}
Examples of usage:
BgRunner.exe php/php-cgi -b 9999
BgRunner.exe redis/redis-server --port 3000
BgRunner.exe nginx/nginx
It's unimaginable that after a decade that Windows still doesn't have a decent way to run commands in background.
start /B command is the most given answer, but the command will be closed when the terminal closed.
Now, Windows 10 have a built-in(you have to install it mannually though) ssh server. you can run
ssh username#localhost "my_backgroud_command --params"
and then CTRL C, close the terminal, the command will continue to run in background.
This is the most decent way I have found so far.
Although not decent enough, because you have to install and configure the ssh server first.
An option I use frequently when I need to run a simple command, or set of commands, in the background and then log off, is to script the command(s) (BAT, CMD, PowerShell, et al. ... all work fine) and then execute the script using Windows native Task Scheduler. Jobs that are executed from the Task Scheduler do not die when you log off. Task Scheduler jobs can be configured to run as "hidden" i.e. the command prompt window will not be displayed. This script + Task Scheduler is a great alternative rather than developing an executable (e.g. yadda.exe) in your favorite development environment (e.g. Visual Studio) when the task at hand is simple and writing a console application to execute a simple command or two would be "overkill" i.e. more work than it's worth.
Just my two cents.
Cheers!
On a windows server here, use a title (in double brackets) , otherwise it will not "release" :
start "" "chrome.exe --parameters" && echo truc
Is there a way to use the popular Console2 cmd.exe replacement for Visual Studio debugging? In other words, when I debug a console app under VS, I want it to use Console2 instead of cmd.exe.
Interesting question. I looked into it, there are some options but none are pretty.
Console.exe takes arguments, so it's possible to start it with a specific tab and execute an arbitrary process. However, this process will always be run within it's own cmd.exe; for example if your program is c:\my.exe and you launch Console as console.exe -t tabname -r c:\myexe Console2 internally calls CreateProcess( ... cmd.exe c:\my.exe ... ), as a result you can't even see the output of my.exe. This is easily solved though: launch it as console.exe -t tabname -r "/k c:\myexe": the /k switch makes the cmd.exe stay active and you can see your program's standard output. (I looked through the source but couldn't find a way to 'attach' a tab to a currently running Console instance, so launching with arguments will always create a new instance, not sure this is what you are looking for?
You can easily modify the project's debugging properties to reflect the above:
Command: /path/to/console.exe
Command Arguments: -t tabname -r "/k $(TargetPath)"
When starting your exe from within VS, it will launch your exe witin a Console session. However the debugging won't work as VS will try to debug console.exe, not my.exe since that is now a different process. Putting a DebugBreak(); as first line in your exe's main() will sort of solve this, as it will present you the option to debug your exe. All in all, this may a bit too much of a hassle to achieve what you want, but i don't think there's another way: Console always spawns a new process, so the only way to get it debugged is to attach the debugger to it after that process started.
Scott Hanselman blogged about this.
He suggests using this value for Console Settings > tabs > Main > Shell :
%comspec% /k ""C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat"" x86
Sadly for me, This does not appear to work for Visual Studio Express 2010, which lacks a vcvarsall.bat file.
Is there any way that a running process can delete its own executable?
For example, I make a console application (single exe) and after doing some tasks it somehow deletes the exe file.
I have to send a single file to someone. And I want it deleted after it does its intended task.
Is there anyway to do it in Windows
One way to do this is to use the MoveFileEx function with the MOVEFILE_DELAY_UNTIL_REBOOT flag and a NULL destination. According to the documentation, this:
registers the lpExistingFileName file to be deleted when the system restarts. If lpExistingFileName refers to a directory, the system removes the directory at restart only if the directory is empty.
process.start("cmd /c ping localhost -n 3 > nul & del filepath")
exit
Explanation :
ping localhost -n 3
Adds a slight delay before executing del filepath. By the time it's triggered, your program has exited.
Replace process.start with whatever command your programming language uses to start programs with arguments.
Replace filepath with the path to your exe.
Replace exit with the command for terminating your program.
===
10yr anniverary edit, if this doesn't work, you must find a way to perform a "process.start" that starts a separate (external) process, not one subordinate to your original calling program: Python, Bash, C, ...... or search for a different language
Replace the search in the catch all with your programming language and you will likely find a suitable guide for this essential step. Please take care to ignore superfluous information as every question may come with obscure specific details that are unrelated to you.
You can use windows scheduler to schedule a task to delete your program after X seconds.
Command line: http://msdn.microsoft.com/en-us/library/bb736357%28VS.85%29.aspx
Or API: http://msdn.microsoft.com/en-us/library/aa383608%28VS.85%29.aspx
You can run another application, which would wait for parent process to terminate, and then delete its executable.
It's possible to do this on Linux. You'll find that it is generally not possible to delete a running executable on Windows. However, you can have Windows delete the EXE for you on the next reboot: http://www.howtodothings.com/computers/a1402-delete-a-running-exe.html
If you want the file deleted after it's been run, you could simply ask the user to delete it. If the reason you want this is as a security measure, then what you're doing is misguided. The user could circumvent this by simply making a copy of the file first.
While it's not possible to self delete a file when it's running it is possible to launch a detached cmd command from the file, then end the file operation before the command executes.
So, if you want to delete a bat file you can just add at the end of the file the line:
start cmd /c del %0
and the file would self destruct.
The start cmd will start a new cmd window (detached from your main process).
The /c tells the windows to execute whatever comes after the /c in the line.
Then the del will delete the file at the path it is given.
The parameter $0 refers to the first command line argument which is usually the name and path to the file that was executed, which is what we want.
(the $0 parameter is the path to the file, you want to pass that to the del command).
Until that exe is in memory, it will not be able to delete itself. However, it can register with the system a task for deleting itself after a set time period of gap when it would be expected to be completing its execution.
I solved this problem (using Visual Basic) by creating a batchfile that is executed while the process is still running, waits 1sec so the program can close itself and than deletes the program.
You might need to modify it for this will delete every thing in the same folder. After your task just call del() and it should work.
Sub del()
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter("del.bat", True)
file.WriteLine("")
file.WriteLine("timeout 1")
file.WriteLine("echo Y | del *.*")
file.Close()
Process.Start("del.bat")
Me.Close()
End Sub
I couldn't find any solutions anywhere else so I'll post my fix here.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[])
{
char* process_name = argv[0];
char command[256] = "start /min cmd /c del ";
strcat(command, process_name);
printf("Attempting to delete self...\n");
system(command);
return 0;
}
Normally, trying to use system to call the command prompt to delete an executable would not work because the command prompt that is spawned is a child process that system executes and waits for a return status.
This method calls the system to start a command prompt process on its own thread.
The /min argument starts the process as "hidden".
The /c argument supplies arguments to the spawned command prompt.
I know this is an old thread, but I hopes those that come here in the future.