How do I use additional binary, such as tee.exe, as command line args with Visual Studio? - visual-studio-2010

While debugging I want to display console output both on console and save a backup in file.
Windows doesn't have tee, but you can add one. Say the folder is c:\bin\ and it works fine. And I have added it into system's PATH.
Problem is setting "[ ]| tee[.exe] output.txt" or " | tee[.exe] output.txt" won't work -- the output.txt is just nowhere to be found. I also tried to add the c:\bin\ path explicitly in VC Directories or environment under debugging and merge environment to be yes.
"> output.txt" works fine.
Anyone has any idea how I can resolve this? Many thanks!

I assume that you're putting the | tee.exe output.txt string in the project property "Debugging | Command Argument".
Unfortunately, that property only supports the redirection operators, not the pipe operator. If you have the | tee.exe output.txt string in the preoperty and run a program that dumps the command line arguments, you'll see that that information is just passed on as the arguments. The "Debugging | Command Argument" doesn't actually get processed by a full-fledged shell (such as cmd.exe) - it's just the IDE supporting some simple redirection (actually, it seems to support more than I expected):
From http://msdn.microsoft.com/en-us/library/kcw4dzyf.aspx:
You can use the following redirection operators in this box:
< file
Reads stdin from file.
> file
Writes stdout to file.
>> file
Appends stdout to file.
2> file
Writes stderr to file.
2>> file
Appends stderr to file.
2> &1
Sends stderr (2) output to same location as stdout (1).
1> &2
Sends stdout (1) output to same location as stderr (2).
You can have a limited version of what you're looking for by redirecting the program's output to a file using >> and using a tail-f command to display whatever gets added to the file. If you do this you'll probably want to call setvbuf( stdout, NULL, _IONBF, 0 ) first thing in main() so that I/O is unbuffered. Otherwise tail -f won't see it until the buffer gets flushed, and I imagine that you'd like to see each output operation as it occurs.
Another option is to crank the console window's "Screen Buffer Height" property up to a large number - one of the first things I do when I get a new Windows machine is set that value to 3000 or so - then debug the program normally and copy/paste the contents of the console window before it closes.

You better NOT use printf for this purpose. Instead, write your own function; taking formatted-input, like printf - having variable number of arguments (...). That function will use printf to display on console, get the buffer written on file, would send to output to debug window and all. You may customize it depending on Debug/Release build.
It may go like (may have some minor mistakes):
void PrintDebuggingInfo(const char* pFormatString, ...)
{
va_list arguments;
char OutputString[1024];
va_start(pFormatString, argument);
vsprintf(OutputString, pFormatString, argument); // Generate string
// Now use `OutputString` as you wish!
}
You may use other variant of vsprintf. Infact all formatted-functions use this function only!

Related

Piping not seem to work with cd | explorer in cmd

I've been learning batch scripting so I came across pipes and I/O redirection.
If this works:
tasklist | find "winword"
Why does this not:
cd | explorer
I expect this command to open explorer at current working directory as cd without any parameters outputs current directory and:
explorer %directory%
opens explorer at %directory%.
Is there something I am doing wrong here?
Open a Command Prompt window, type find "blah" and press Enter; you'll see it awaits user/keyboard/console input, which STDIN points to (press Ctrl+Z and Enter to end the prompt). Then type echo blah and press Enter; you'll notice the text blah is printed, so there is display/console output; this is pointed to by STDOUT. A pipe | takes the data at STDOUT from the left-side command and redirects it into STDIN for the right-side command.
Now type explorer into the Command Prompt window; of course an Explorer Window pops up, but what happens in the Command Prompt? right, nothing, it does not await any input at STDIN. So you can pipe to it but it will not care as it does not read at STDIN. In fact, GUI applications do generally not use STDIN and STDOUT, because these things are intended for command line applications.
Yet another example: in a Command Prompt window, type echo C:\Windows; quite obvious what will happen; then type echo C:\Windows| dir; what happens? dir returns the contents of the current directory but not of C:\Windows. Why? well, let's type dir first and see what happens: yes, dir shows the contents of the current directory, and it does not await console input; so at the right side of the pipe it receives data at STDIN but it simply doesn't care. You can try using dir "C:\some\other\folder", without and with the pipe, the output is just the same, STDIN is ignored here.
The echo/dir example also demonstrates the difference between console input (STDIN) and command line arguments or parameters: the path in the command line dir "C:\some\other\folder" is such an argument, and you cannot replace it by data from STDIN. To understand why, you need to distinguish between parse time (when the command is read and parsed by the interpreter) and run time (when the command is actually executed): arguments already have to be present at parse time, whilst STDIN is only relevant during run time, which is later. So we can say they just never meet.
This also reflects the situation with your attempt cd | explorer: the latter accepts command line arguments (which anyway need to be available before execution, so at parse time), but it doesn't care about STDIN. Also the STDOUT data from cd isn't available before execution (but only during run time), so it would arrive too late anyway...

fastest command, which accepts pipe, but generates no text on StdOut & StdErr

Which command in Windows command script (.cmd) accepts pipe (so, no error "The Process tried to write to a nonexistent pipe." generated), but generates no output itself, including output to StdErr? I need to not touch normal StdErr output (keep in mind, pipe transports only StdOut). I can't use null device, due to it's not installed in the system.
For example, command|rem generates mentioned error. But I want no error output, except generated by command, so rem is not suitable command for needed purpose.
Main aim is the script speed. So, don't offer extensive constructions, please.
should be break(or set/p= ?) as it is internal command prompt command (i.e. no external process started ) and generally do nothing.Though I suppose if you are searching for executable packed with the windows answer will be different.
The cd . command is what you are looking for. I used it to create empty files. This way, command | cd . works and echo Hello >&2 | cd . show "Hello" in the screen! This works as a filter that just blocks Stdout (interesting).

Cant get output of command to command line itself?

I have a command typed in the command line for example: -
texteditor --help
This command executes and a window flashes and no output is given on the command line when i am expecting one. On further inspection i find that the command does give an output which i get through
texteditor --help > output.txt
This means that the command does yield an output. I have also included the path in the Environment Variables. How can i give the output to the cmd without reading from the file i.e. that i type
texteditor --help
and get the output in the same console itself.
You could try something like
FOR /F %X ('texteditor --help') DO ECHO %X
This should take the output from texteditor and echo it, line by line, on the console. If you're going to put it in a batch file, double the percent symbols.
EDITED AGAIN
I can only imagine the texteditor program is writing to a non-standard place. Normally, programs write normal messages to stdout (stream 1) and write error messages to stderr (stream 2). I obviously do not know what your particular program does, so to investigate it, I would do this:
texteditor --help 2> str2.txt 1> str1.txt
Thne you will have two files, str2.txt and str1.txt. Depending on what each contains afterwards, you should be able to see which stream you need to capture.
EDITED
In the light of your comment, maybe try this to output to console:
texteditor --help > con
I am not sure I understand what you mean by "How can I give the output to the cmd", but you can save the output of the command into the Windows Clipboard ready to paste into other applications like this:
texteditor --help | CLIP

What is a simple explanation for how pipes work in Bash?

I often use pipes in Bash, e.g.:
dmesg | less
Although I know what this outputs, it takes dmesg and lets me scroll through it with less, I do not understand what the | is doing. Is it simply the opposite of >?
Is there a simple, or metaphorical explanation for what | does?
What goes on when several pipes are used in a single line?
Is the behavior of pipes consistent everywhere it appears in a Bash script?
A Unix pipe connects the STDOUT (standard output) file descriptor of the first process to the STDIN (standard input) of the second. What happens then is that when the first process writes to its STDOUT, that output can be immediately read (from STDIN) by the second process.
Using multiple pipes is no different than using a single pipe. Each pipe is independent, and simply links the STDOUT and STDIN of the adjacent processes.
Your third question is a little bit ambiguous. Yes, pipes, as such, are consistent everywhere in a bash script. However, the pipe character | can represent different things. Double pipe (||), represents the "or" operator, for example.
In Linux (and Unix in general) each process has three default file descriptors:
fd #0 Represents the standard input of the process
fd #1 Represents the standard output of the process
fd #2 Represents the standard error output of the process
Normally, when you run a simple program these file descriptors by default are configured as following:
default input is read from the keyboard
Standard output is configured to be the monitor
Standard error is configured to be the monitor also
Bash provides several operators to change this behavior (take a look to the >, >> and < operators for example). Thus, you can redirect the output to something other than the standard output or read your input from other stream different than the keyboard. Specially interesting the case when two programs are collaborating in such way that one uses the output of the other as its input. To make this collaboration easy Bash provides the pipe operator |. Please note the usage of collaboration instead of chaining. I avoided the usage of this term since in fact a pipe is not sequential. A normal command line with pipes has the following aspect:
> program_1 | program_2 | ... | program_n
The above command line is a little bit misleading: user could think that program_2 gets its input once the program_1 has finished its execution, which is not correct. In fact, what bash does is to launch ALL the programs in parallel and it configures the inputs outputs accordingly so every program gets its input from the previous one and delivers its output to the next one (in the command line established order).
Following is a simple example from Creating pipe in C of creating a pipe between a parent and child process. The important part is the call to the pipe() and how the parent closes fd1 (writing side) and how the child closes fd1 (writing side). Please, note that the pipe is a unidirectional communication channel. Thus, data can only flow in one direction: fd1 towards fd[0]. For more information take a look to the manual page of pipe().
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
int main(void)
{
int fd[2], nbytes;
pid_t childpid;
char string[] = "Hello, world!\n";
char readbuffer[80];
pipe(fd);
if((childpid = fork()) == -1)
{
perror("fork");
exit(1);
}
if(childpid == 0)
{
/* Child process closes up input side of pipe */
close(fd[0]);
/* Send "string" through the output side of pipe */
write(fd[1], string, (strlen(string)+1));
exit(0);
}
else
{
/* Parent process closes up output side of pipe */
close(fd[1]);
/* Read in a string from the pipe */
nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
printf("Received string: %s", readbuffer);
}
return(0);
}
Last but not least, when you have a command line in the form:
> program_1 | program_2 | program_3
The return code of the whole line is set to the last command. In this case program_3. If you would like to get an intermediate return code you have to set the pipefail or get it from the PIPESTATUS.
Every standard process in Unix has at least three file descriptors, which are sort of like interfaces:
Standard output, which is the place where the process prints its data (most of the time the console, that is, your screen or terminal).
Standard input, which is the place it gets its data from (most of the time it may be something akin to your keyboard).
Standard error, which is the place where errors and sometimes other out-of-band data goes. It's not interesting right now because pipes don't normally deal with it.
The pipe connects the standard output of the process to the left to the standard input of the process of the right. You can think of it as a dedicated program that takes care of copying everything that one program prints, and feeding it to the next program (the one after the pipe symbol). It's not exactly that, but it's an adequate enough analogy.
Each pipe operates on exactly two things: the standard output coming from its left and the input stream expected at its right. Each of those could be attached to a single process or another bit of the pipeline, which is the case in a multi-pipe command line. But that's not relevant to the actual operation of the pipe; each pipe does its own.
The redirection operator (>) does something related, but simpler: by default it sends the standard output of a process directly to a file. As you can see it's not the opposite of a pipe, but actually complementary. The opposite of > is unsurprisingly <, which takes the content of a file and sends it to the standard input of a process (think of it as a program that reads a file byte by byte and types it in a process for you).
In short, as described, there are three key 'special' file descriptors to be aware of. The shell by default send the keyboard to stdin and sends stdout and stderr to the screen:
A pipeline is just a shell convenience which attaches the stdout of one process directly to the stdin of the next:
There are a lot of subtleties to how this works, for example, the stderr stream might not be piped as you would expect, as shown below:
I have spent quite some time trying to write a detailed but beginner friendly explanation of pipelines in Bash. The full content is at:
https://effective-shell.com/docs/part-2-core-skills/7-thinking-in-pipelines/
A pipe takes the output of a process, by output I mean the standard output (stdout on UNIX) and passes it on the standard input (stdin) of another process. It is not the opposite of the simple right redirection > which purpose is to redirect an output to another output.
For example, take the echo command on Linux which is simply printing a string passed in parameter on the standard output. If you use a simple redirect like :
echo "Hello world" > helloworld.txt
the shell will redirect the normal output initially intended to be on stdout and print it directly into the file helloworld.txt.
Now, take this example which involves the pipe :
ls -l | grep helloworld.txt
The standard output of the ls command will be outputed at the entry of grep, so how does this work?
Programs such as grep when they're being used without any arguments are simply reading and waiting for something to be passed on their standard input (stdin). When they catch something, like the ouput of the ls command, grep acts normally by finding an occurence of what you're searching for.
Pipes are very simple like this.
You have the output of one command. You can provide this output as the input into another command using pipe. You can pipe as many commands as you want.
ex:
ls | grep my | grep files
This first lists the files in the working directory. This output is checked by the grep command for the word "my". The output of this is now into the second grep command which finally searches for the word "files". Thats it.
The pipe operator takes the output of the first command, and 'pipes' it to the second one by connecting stdin and stdout.
In your example, instead of the output of dmesg command going to stdout (and throwing it out on the console), it is going right into your next command.
| puts the STDOUT of the command at left side to the STDIN of the command of right side.
If you use multiple pipes, it's just a chain of pipes. First commands output is set to second commands input. Second commands output is set to next commands input. An so on.
It's available in all Linux/widows based command interpreter.
All of these answere are great. Something that I would just like to mention, is that a pipe in bash (which has the same concept as a unix/linux, or windows named pipe) is just like a pipe in real life.
If you think of the program before the pipe as a source of water, the pipe as a water pipe, and the program after the pipe as something that uses the water (with the program output as water), then you pretty much understand how pipes work.
And remember that all apps in a pipeline run in parallel.
Regarding the efficiency issue of pipe:
A command can access and process the data at its input before previous pipe command to complete that means computing power utilization efficiency if resources available.
Pipe does not require to save output of a command to a file before next command to access its input ( there is no I/O operation between two commands) that means reduction in costly I/O operations and disk space efficiency.
If you treat each unix command as a standalone module,
but you need them to talk to each other using text as a consistent interface,
how can it be done?
cmd input output
echo "foobar" string "foobar"
cat "somefile.txt" file *string inside the file*
grep "pattern" "a.txt" pattern, input file *matched string*
You can say | is a metaphor for passing the baton in a relay marathon.
Its even shaped like one!
cat -> echo -> less -> awk -> perl is analogous to cat | echo | less | awk | perl.
cat "somefile.txt" | echo
cat pass its output for echo to use.
What happens when there is more than one input?
cat "somefile.txt" | grep "pattern"
There is an implicit rule that says "pass it as input file rather than pattern" for grep.
You will slowly develop the eye for knowing which parameter is which by experience.

Redirection Doesn't Work

I want to put my program's output into a file. I keyed in the following :
./prog > log 2>&1
But there is nothing in the file "log". I am using the Ubuntu 11.10 and the default shell is bash.
Anybody know the cause of this AND how I can debug this?
There are many possible causes:
The program reads the input from log file while you try to redirect into it with truncation (see Why doesn't "sort file1 > file1" work?)
The output is buffered so that you don't see data in the file until the output buffer is flushed. You can manually call fflush or output std::flush if using C++ I/O stream etc.
The program is smart enough and disables output if the output stream is not a terminal.
You look at the wrong file (i.e. in another directory).
You try to dump file's contents incorrectly.
Your program outputs '\0' as the first character so the output appears to be empty, even though there is some data.
Name your own.
Your best bet is to run this application under a debugger (like gdb) or use strace or ptrace (or both) and see what the program is doing. I mean, really, output redirection works for the last like 40 years, so the problem must be somewhere else.

Resources