Suppress system("ping") output in C++ - c++

I have written a simple program that pings three sites and then reacts to whether they are reachable or not.
My question is: can I suppress system("ping ")'s output? I have written my code in C++ as I know that language the best. Currently the code opens the ping.exe running the system command. If I can prevent the output from showing up while it still pings that would be ideal.
I am eventually going to turn this program in a windows service that is why I would like to suppress both the command line console window as well as suppress the ping output. Thanks.

Try doing system("ping host > nul") (nul is windows equivalent of UNIX /dev/null).

Generally, if you're going to call another program but don't want it to act like std::system, you're going to need a platform-specific function like fork()/exec() on UNIX or CreateProcess() on Windows. These functions give you control over how the other program runs, for instance, that it not show output or not create a console window, etc.

You can use system command like below to suppress the output of ping command.
system("ping 100.100.100.100 > response.dat");
Above command pings IP address 100.100.100.100 and directs the output to a file called response.dat. In response.dat you can see the response of ping command.

Do system( "ping site.com >nul 2>nul" ); and check the value the shell returns.
if the ping succeeds, the shell will return 0, else it will return 1.
I would be more detailed, but Vis Studio is reinstalling itself. :)
There's also a way to hide the console window using the Win API to exec the command, but...
I do not remember the details.
Edit:
I'm still waiting for the MSVS install process, so... :)
Use CreateProcess with the DETACHED_PROCESS flag for the dwCreationFlags parameter to hide the console window.
After you call create process, you'll have to use WaitForSingleObject on the process handle to wait for the ping to complete. The last parameter to CreateProcess should have a pointer to process information that contains the process handle. (Assuming CreateProcess was successful) You have to wait for the command to complete. Once it's complete, you can use the process handle to get the return value, though I'm too time contstrained to tell you how to do that at this point.

When you get over to Windows and call CreateProcess(), be sure to set:
lpStartupInfo->wShowWindow = SW_HIDE;
This will ensure that any windows created by the new process are hidden.
Using the DETACHED_PROCESS flag will prevent the new process from inheriting your application's console, but that does not prevent the new process from creating a new console. Not sure what ping would do, but best to remove all doubt by using SW_HIDE.

You could also use this way, this will return the output in a file and doesn't show up a console windows and freezes the main application which is really usefull.
At first you need to include the Windows header using;
#include <Windows.h>
then send a ping command and write the output into a file like this;
WinExec("ping google.com > file.dat", SW_HIDE);
This will send a ping command to google.com and writes the output to the file 'file.dat' in the directory of your current running program. So you could change file.dat to any file or filepath you want and of course you could change the ping command. The > character means that the output of the command needs to be wrote in the file path behind it.
If you want to show the console window and freeze the application while running the ping command you need to use the following line of code instead of the WindExec() code;
system("ping google.com > file.dat");

Related

How to open separate command prompt consoles for two seperate CreateProcess() API calls

I've a caller.EXE from within which I do 2 calls of "CreateProcess() APIs like this. Both the CReateProcess() APIs are trying to launch console application EXEs.
Caller.cpp (Caller.EXE) has teh following code in it::
...................
..................
CReateProcess( Callee_1) // For launching a console EXE which starts running in the same CMD prompt window where I've the main "CAller.EXE" running.
..............
<Few lines of C++ logic>
........
CReateProcess(Callee_2) // For launching another console EXE .
Now the problem is that I want the 2nd CreateProcess(Callee_2) call to actually launch a different command prompt but what is happening here is that the 2nd CreateProcess(Callee_2) call is not launching anotehr CMD prompt. The same CMD prompt is execiting the Callee_1 in it.
I see that in my Caller code CreateProcess() is successful for both the times.
I want the 2nd CreateProcess(Callee_2) call to actually
launch a different command prompt. How do I achieve that? I think I
should give it as part of the input parameters to
CreatyeProcess(Callee_2) call.
I'm not very knowledgeable about Windows or MSDN, but as far as I remember,
CReateProcess( Callee_1)
which should actually be CreateProcess(), taken one parameter DWORD fdwCreate , where,
CREATE_NEW_CONSOLE
can be used to specify that the new process should have a new console, instead of inheriting the parent's console.
Maybe this link is helpful to you.

Open the terminal and execute commands via C programming

Does someone know how to open the terminal and execute several commands using a C program ?
I have a program in C and another sets of commands executed by the terminal. I need to combine them into one program in C.
I'm using Ubuntu 10.04.
Thanks!
Your question may be somewhat misleading.
Because you want to run all the terminal commands in the c-code, perhaps you actually have only textual input / output with these commands. If so, you probably do not need the terminal.
I use popen when the output of the (terminal) program is a text stream. It is probably the easiest to use. As an example:
...
const char* cmndStr = "ls -lsa";
FILE* pipe = popen(cmndStr, "r");
...
The popen instruction executes the command in the cmndStr, and any text written to the commands (ls -lsa) standard output, is redirected into the pipe, which is then available for your C program to read in.
popen opens a separate process (but without a terminal to work in, just the pipe)
'Fork' is another way to launch a separate process, with some control over the launched processes' std i/o, but again, I think not a terminal.
On the other hand, if your output is not a simple text stream, maybe you can get by with a output-only dedicated terminal screen to accommodate special output activity. For instance, when I work with ncurses:
I manually open a terminal in the conventional way, and in the terminal
issue the command "tty" to find out the device name, and
issue a "cd" to set the focus to the working dir.
dmoen#C5:~$ tty
/dev/pts/1
dmoen#C5:~$ cd work
dmoen#C5:~/work$
Then I start my program (in a different tty), and let the program know which device I want it to use for the special output (i.e. /dev/pts/1 ) ... I typically use command line parameters to tell my program which pts or extra terminals I want it to use, but environment variables, pipes, in/out redirection, and other choices exist.
I have not tried (lately) to launch a terminal (as suggested by smrt28), except in shell. I believe this will work, but I do not see how the output from the terminal command (ls in the example) would be delivered back to your program. popen trivially delivers a text stream.
A long time ago, I used a device called 'pty' which works like a terminal, but I don't remember how to connect it usefully.
There is a set of 'exec' commands ... see man exec. To connect them back to your program, you will probably work with files, or perhaps redirecting i/o. Too many choices to list here.
And also, maybe you can connect these commands with your c program using shell pipes.
Check "man xterm", parameter -e. Then, in C, you can:
system("xterm -e ls")

Attach a terminal to created thread, in C++ on Linux

I'm developing a chat server in C++. The programme is built and run from a terminal. As running in the terminal, I can write to this terminal normally using 'printf'. Some of the information written to this terminal are the alerts of new incoming connections, outgoing connections, etc.
Now I need to get the keyboard input so that admin can type commands to see the values of variables in the chat server. I intend to create a new thread and attach a new terminal to it. A suggestion is to call system("gnome-terminal"), but it requires a little delay with sleep(), doesn't seem to be a good choice because all the contents redirected to this gnome-terminal will be considered as bash commands. And I don't know how to attach the terminal opened by 'system'` command to the thread.
Any simple way to attach a terminal to created thread?
Maybe have a read of this on how to use pipes in Linux
http://linuxprograms.wordpress.com/tag/pipes/
As partially answered in this question: Avoid gnome-terminal close after script execution?
There is a good option like this:
(1) Use the main terminal for normal input/ouput.
(2) Create log file (log.file) before calling 'tail'
(3) Use 'tail' command for showing log contents (log files)
//c++ code
system("gnome-terminal -e \"bash -c 'tail -f log.file'\"");
(4) Append the content to 'log.file' to tell 'tail' to show it up.

Is it possible to send command to console window in which my program is running?

I know the system() function but that creates it's own environment so every variable set here isn't forwarded to main console. I wonder is it possible to send command as it would be written by the user or as it would be executed by *.bat file ?
The reason I need this is that I look for a way to set env variable of parent CMD process. And yes I know that system doesn't want me to do it, but maybe there is a some workaround for that...
Idea is to create app that would set as a variable anything that is send to it via input pipe, like this:
echo Bob| setvar name
so then:
echo %name%
would produce Bob
The whole idea is to make easier setting a variable from any program output (I know how to do it with for command) with taking account of peculiarities with special batch characters like ^!% since these are allowed in file names. It would make simpler many cmd scripts.
You can certainly run programs in the same console window as your program. That's the default behavior for CreateProcess. MSDN has more details on what happens between related processes sharing a console. You'll probably want to wait for the child process to terminate before continuing to run your own program.
However, that won't help with your real goal. The window where a program runs has absolutely nothing to do with the environment variables of any of its ancestor processes. You'll have to look elsewhere for a solution to your real problem.

How to simulate interaction with console programmatically?

I want to know how to programmatically execute commands (like "dir C:\" or "shutdown -r", etc.) in Windows' Command Prompt (CMD) and retrieve the resulted output, without displaying the black CMD window of course.
I suspect ->this link<- contains the list of required APIs, but I'm not sure which ones to pick, so need your assistance.
Basically this is what I need it for: I want to write simple client-server application (WinSock) where user can sit on the client end and execute commands in (and read replies from) the command prompt of server. Yes - just like Telnet works, but without Telnet, just Win32 API.
Suppose user wants to execute "dir" command on server. He types "dir" on client application, which sends request to the server application, where the command will be executed (as if it was physically typed in command prompt of server) and the output text will be sent back to the client application.
You are basically trying to reimplement one of the many possible uses of netcat. By running on the windows system in a command prompt:
nc -l -L -e cmd -p 5555
and then running from another system
nc 192.168.1.xxx 5555
with 192.168.1.xxx being the IP address of the windows machine you can do exactly what you are talking about: whatever you type will be "typed" on the windows machine and you will get the output from the remotely executed commands. You can also run netcat in an hidden window.
Note that because of this feature some antivirus blocks the netcat program... it has been apparently used by malicious software to transform PC of victims into slave bots.
Note also that routing input/output directly to cmd (the XP shell) is extremely dangerous as there is no authentication of any type: anyone can connect to port 5555 and execute commands on the machine, something you really don't want to allow unless you're in a very controlled environment.
Although this answer is not a good one for portable software, it works exactly the way you need it if you are sure everything is ok:
int system(const char *command);
This function executes command in shell (CMD in windows) if available.
By "if everything is ok" I mean you have a shell in your OS and it is available to you. Generally, this should be true for windows.
If you call it with NULL, it will give non-zero if shell is available. If you give an actual command, it either returns -1 indicating an error (for example couldn't spawn a process), or return status of the command which should be OS dependent. Perhaps what you would be most concerned with is "if the command failed" and you should be good by checking the return value against 0 (0 being good).
Note that to get the output of the command, and you need to save the output somewhere. For example execute the dir command like this:
error = system("dir > temp.txt 2>&1");
and then retrieve its output from temp.txt.