how to get back stdout after piping it with dup? - c++

int mypipe[2];
pipe(mypipe);
int dupstdout=dup2(mypipe[1],1);
cout<<"hello";//not printed on terminal
fflush(stdout);
now how to print again on terminal or redirect mypipe[0] to stdout?

Best to save a copy of standard out and restore it later. If dup2 closes your last copy of stdout, you might not be able to get it back (e.g., no controlling terminal, chroot'd and no access to /dev nor /proc, stdout was an anonymous pipe to begin with, etc.).
int mypipe[2];
pipe(mypipe);
int savstdout=dup(1); // save original stdout
dup2(mypipe[1], 1);
printf("hello"); // not printed on terminal
fflush(stdout);
dup2(savstdout, 1); // restore original stdout

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
int main() {
int mypipe[2];
pipe(mypipe);
int dupstdout=dup2(mypipe[1], 1);
printf("hello");//not printed on terminal
fflush(stdout);
close(dupstdout);
int fd = open("/dev/tty", O_WRONLY);
stdout = fdopen(fd, "w");
printf("hello again\n");
}
Anyway, it's better to not close stdout.
If a descriptor passed as a second argument to dup2() is already opened, dup2() closes it ignoring all errors. It's safer to use close() and dup() explicitly.

Related

multiplexing unnamed pipe and other file descriptors using select

I'm trying to multiplex an unnamed pipe with some other file descriptors.
The problem is that the pipe file descriptor always appears in the result of select. In other words the event-loop reads from pipe for infinite times. Here is a metaphor of what I want to do, and what actually happens.
#include <iostream>
#include <stdlib.h>
#include <algorithm>
#include <stdio.h>
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <unistd.h>
using namespace std;
int main(){
fd_set master; // master file descriptor list
fd_set read_fds; // temp file descriptor list for select()
FD_ZERO(&master); // clear the master and temp sets
FD_ZERO(&read_fds);
int fdmax; // maximum file descriptor number
int pfd[2];
if(pipe(pfd)!=0) {cout<<"Unable to create a pipe.\n",exit(1);};
FD_SET(0, &master);
FD_SET(pfd[0],&master);
fdmax=pfd[0];
if(fork()){//Parent
for (;;){
read_fds = master; // copy it
if (select(fdmax+1, &read_fds, NULL, NULL, NULL) == -1) {
perror("select");
exit(4);
}
for(int i = 0; i <= fdmax; i++) {
if (FD_ISSET(i, &read_fds)) {
int n;
char buff[200];
if (i==pfd[0]){
close(pfd[1]);
n=read(pfd[0],buff,sizeof(buff));
buff[n]=0;
cout<<"Read from pipe:"<<buff<<endl;
}else if(i==0){
n=read(0,buff,sizeof(buff));
buff[n]=0;
cout<<"Read from std:"<<buff<<endl;
}
}
}
}
}else{//Child
usleep(50000);
char buff[200]="This is a simple sample.";
close(pfd[0]);
write(pfd[1],buff,sizeof(buff));
close(pfd[1]);
exit(0);
}
}
First of all, the read() call can read less than number of bytes specified in the last argument ant id does not automatically append zero-byte terminator, so your receiving code can easily access uninitialized memory in buff[] and after it (if there is no zero byte). You need to check return value when calling read and use only so many bytes from buffer.
Then, the select call returns when any file descriptor in the readfds set won't block on subsequent read. Which includes end-of-file condition. This likely happens in your case, when the forked process closes its fd. See this SO question too.
Could it be the reason for the problem you encounter? Checking return value when calling read make this clear to you, as read returns zero if-and-only-if the fd reached end of file.
Last detail – it does not make much sense to close pfd[1] only after pfd[0] is returned in the readfds. You should close it immediately after the fork, so it remains open in the child process only if you have no use for it in the parent process.

Linux pipe, fork and execlp: how to get the value written into stream 1

I use a function (L) to execute another program (K) through execlp().
In the K program, the result is written into stream 1:
write(1, (char *)&o, sizeof(int));
Since after execlp(), the remaining part of L won't be executed, how could I get the result written in stream 1?
Don't ask me why I need to do it this way. It's the requirement for a project.
I followed your guys advices, but now the problem is, the way the K program get the arguments are from streams(one standard stream, one other stream), I'm using pipes to write arguments into corresponding streams (it's done by the parent).
After the child exec, in the parent part, I read from stream 0 (the K program writes its result back in stream 1). But what I could get is what the parent wrote into the stream, not what the K program write back.
What's wrong? Do I need to add another pipe?
Thanks!!
The key insight, which Jonathan Leffler mentioned in his comment, is that you need to fork the program which is running L before you call execlp().
After the fork, the parent continues to execute the rest of L, and the child morphs into the program K by calling execlp(), which should never return unless there is an error.
Thus, the assertion that "the remaining part of L won't be executed" is incorrect. It will get executed, in the parent process if you write the function L correctly.
Update: Since the OP made his question more specific, I am appending to this answer.
If you want to retrieve what the child process wrote to stdout (fd 1), you need to create a new pipe before the fork, and copy the writing end of this pipe into the child's stdout.
Here is an example program, slightly modified from the pipe man page.
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int
main(int argc, char *argv[])
{
int pipefd[2];
pid_t cpid;
char buf;
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
cpid = fork();
if (cpid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (cpid == 0) { /* Child writes into the pipe */
close(pipefd[0]); /* Close unused read end */
// Copy the writing end of the pipe into STDOUT for the child.
dup2(pipefd[1], STDOUT_FILENO);
// Execute your program L here, and its stdout will be captured by the pipe.
const char* message = "Child is speaking to stdout!";
write(STDOUT_FILENO, message, strlen(message));
write(STDOUT_FILENO, "\n", 1);
close(pipefd[1]);
_exit(EXIT_SUCCESS);
} else { /* Parent reads child's stdout from the pipe */
close(pipefd[1]); /* Close unused write end */
// Here the parent process is reading the child's stdout.
while (read(pipefd[0], &buf, 1) > 0)
write(STDOUT_FILENO, &buf, 1);
wait(NULL); /* Wait for child */
exit(EXIT_SUCCESS);
}
}

Where does "printf" write in a Windows Non-console Application?

If I choose to create a Windows Non-console Application, and implement printf/cout in the code, where does the printf/cout write? Does it write to the stdout buffer? If yes, is there any way to read it from stdout and print it to some text file or do a MessageBox with the text (just to verify that I have read it correctly)?
EDIT:: Just to clarify that I do not want to redirect the output anywhere. I would like to know, where does printf/cout write? And if it writes to some default buffer, is there a way to read the output, just to verify that I have read the correct output and from the correct buffer. Please, do not give me solutions to redirect the "stdout".
Under Windows stdout is a wrapper to the low-level functions accessing the handle returned by GetStdHandle(STD_OUTPUT_HANDLE).
When starting a non-console application by double-clicking (I tried under Windows 7, 64 bit) then GetStdHandle(STD_OUTPUT_HANDLE) will return an invalid handle. This means that printf and other commands will write nothing at all but the low-level functions internally called by printf will return an error code.
However as already said even a non-console program can be started the following way:
program_name > output_file.txt
In this case the printf output will be written to the output file.
-- EDIT --
If you wish to "catch" the printf() output and write it to MessageBox() there are two ways to achieve this:
The first one is running the program twice while the input of one instance is the standard output of the other one. The behavior could be explained by the following command line:
program_name | program_name /msgbox
The second possibility works without running two programs and without running the program twice: You may hook file handle #1. This should be at least possible when using msvcrt.dll:
HANDLE hRead,hWrite;
CreatePipe(&hRead,&hWrite,NULL,0);
dup2(_open_osfhandle(hWrite,O_WRONLY),1);
// Now printf() output can be read from handle hRead
printf("Hello world 2!\n");
// In a separate thread do:
ReadFile(hRead,...);
Since your question seems to be just for information, a windows app without a console, has its stdout, stderr handles closed. Any function that tries to output to those handles, simply gets called, checks for an open handle, finds it closed, and returns without doing anything else.
You might say, your output in this case ends up nowhere to be found :)
If you want to read this output, then you need to open the handles either by allocating a console, or use one of the methods described here.
I am developing a visual engine and I use the following two things as a substitution for the standard input/output between pc and user that you get in console application.
1: Use sprintf (int sprintf ( char * str, const char * format, ... )). What it does is print into a string instead of stdout(you don't have to use a temporary file). After this you can use MessageBox with the string where you just printed to.
2: Make an actual console window(while keeping the main one) and redirect the stdin, stdout and stderr from the main window to the console. Here is a class for construction:
ConsoleWindowClass.h:
#pragma once
#include <windows.h>
#include <stdio.h>
#include <fcntl.h>
#include <io.h>
#include <iostream>
#include <fstream>
class ConsoleWindowClass
{
public:
ConsoleWindowClass(void);
~ConsoleWindowClass(void);
void Create();
};
ConsoleWindowClass.cpp:
#include "ConsoleWindowClass.h"
using namespace std;
// maximum mumber of lines the output console should have
static const WORD MAX_CONSOLE_LINES = 500;
ConsoleWindowClass::ConsoleWindowClass(void)
{
Create();
}
ConsoleWindowClass::~ConsoleWindowClass(void)
{
}
void ConsoleWindowClass::Create()
{
int hConHandle;
long lStdHandle;
CONSOLE_SCREEN_BUFFER_INFO coninfo;
FILE *fp;
// allocate a console for this app
AllocConsole();
// set the screen buffer to be big enough to let us scroll text
GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE),&coninfo);
coninfo.dwSize.Y = MAX_CONSOLE_LINES;
SetConsoleScreenBufferSize(GetStdHandle(STD_OUTPUT_HANDLE),coninfo.dwSize);
// redirect unbuffered STDOUT to the console
lStdHandle = (long)GetStdHandle(STD_OUTPUT_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
fp = _fdopen( hConHandle, "w" );
*stdout = *fp;
setvbuf( stdout, NULL, _IONBF, 0 );
// redirect unbuffered STDIN to the console
lStdHandle = (long)GetStdHandle(STD_INPUT_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
fp = _fdopen( hConHandle, "r" );
*stdin = *fp;
setvbuf( stdin, NULL, _IONBF, 0 );
// redirect unbuffered STDERR to the console
lStdHandle = (long)GetStdHandle(STD_ERROR_HANDLE);
hConHandle = _open_osfhandle(lStdHandle, _O_TEXT);
fp = _fdopen( hConHandle, "w" );
*stderr = *fp;
setvbuf( stderr, NULL, _IONBF, 0 );
// make cout, wcout, cin, wcin, wcerr, cerr, wclog and clog
// point to console as well
ios::sync_with_stdio();
}
After this, calling printf() will print the string into the console. You can also use the console to type strings into it and they will be usable from the main window(use multi-threading so that scanf won't pause your main program).
printf or cout always print to stdout.
You need to start the program from command line and pipe its output to a text file to make it readable.
Otherwise you would need an outputstream to a file in tmp to be generated inside your code.
Piping can be done the following way (if your apps name would be foo):
foo > log.txt
You could then read the file log.txt if you navigate to its directory which can be found with
dir

How to prevent buffer overflow in C/C++?

I am using the following code to redirect stdout to a pipe, then read all the data from the pipe to a buffer. I have 2 problems:
first problem: when i send a string (after redirection) bigger then the pipe's BUFF_SIZE, the program stops responding (deadlock or something).
second problem: when i try to read from a pipe before something was sent to stdout. I get the same response, the program stops responding - _read command stuck's ...
The issue is that i don't know the amount of data that will be sent to the pipe after the redirection.
The first problem, i don't know how to handle and i'll be glad for help. The second problem i solved by a simple workaround, right after the redirection i print space character to stdout. but i guess that this solution is not the correct one ...
#include <fcntl.h>
#include <io.h>
#include <iostream>
#define READ 0
#define WRITE 1
#define BUFF_SIZE 5
using namespace std;
int main()
{
int stdout_pipe[2];
int saved_stdout;
saved_stdout = _dup(_fileno(stdout)); // save stdout
if(_pipe(stdout_pipe,BUFF_SIZE, O_TEXT) != 0 ) // make a pipe
{
exit(1);
}
fflush( stdout );
if(_dup2(stdout_pipe[1], _fileno(stdout)) != 0 ) //redirect stdout to the pipe
{
exit(1);
}
ios::sync_with_stdio();
setvbuf( stdout, NULL, _IONBF, 0 );
//anything sent to stdout goes now to the pipe
//printf(" ");//workaround for the second problem
printf("123456");//first problem
char buffer[BUFF_SIZE] = {0};
int nOutRead = 0;
nOutRead = _read(stdout_pipe[READ], buffer, BUFF_SIZE); //second problem
buffer[nOutRead] = '\0';
// reconnect stdout
if (_dup2(saved_stdout, _fileno(stdout)) != 0 )
{
exit(1);
}
ios::sync_with_stdio();
printf("buffer: %s\n", buffer);
}
Your problem is that you are using blocking I/O calls, while both ends of the pipe are connected to the same process. If you don't know how much data there will be, this is just a deadlock situation waiting to happen.
printf is a blocking call, which means that it will not return until all data has been written to the output device (the pipe in this case), or until a write error is signalled (for example, the other end of the pipe is closed).
_read works similarly. It only returns when it has a full buffer worth of data or it knows that the end of the input has been reached (which can be signalled by closing the write-end of the pipe).
The only ways around this are
to use non-blocking I/O (which is not feasible if you don't have access to the code that calls printf), or
to ensure the reading and writing happens in different processes or threads, or
to use a temporary file for buffering, instead of the buffer of a pipe.
Pipes are unidirectional. Ie. you can either write to a pipe (x)or you can read from it.
To simulate a pipeline, try the following (the below is C, not C++):
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc)
{
int pfds[2];
pipe(pfds);
if (!fork()) {
close(1); /* close stdout, check for errors */
dup(pfds[1]); /* make stdout same as pfds[1], dup reuses lowest fd */
close(pfds[0]); /* not needed */
execlp("ls", "ls", NULL); /* or write() in whatever way you want */
} else {
close(0); /* close stdin, check for errors please! */
dup(pfds[0]); /* make stdin same as pfds[0] */
close(pfds[1]); /* not needed on this end */
execlp("wc", "wc", "-l", NULL); /* or read() */
}
return 0;
}
[edit] By the way, your code does not overflow a buffer. Its only relation to buffer overflow is that you're reading into a statically allocated array...if you read() more than sizeof buffer elements, then you'll run into problems.
You must use non-blocking I/O if you don't want read or write to be blocked in this case.

freopen: reverting back to original stream

I needed to forward stdout to different files to separate some prints produced and the reverting back to normal stdout.
I used freopen to switch to the file in this way:
char name[80];
memset(name, 0, 80);
strcpy(name, "./scripts/asm/");
strcat(name, m_func->m_name->m_value);
strcat(name, ".shasm");
freopen(name, "w", stdout);
And it actually works, but at the end of the process (mind that stdout is redirected many times in the previous same way) I'm not able to revert it to original stdout. I tried the following:
freopen("/dev/stdout", "w", stdout);
but it doesn't seem to work.. just for information I'm developing on macosx.
What should I do?
Thanks in advance
This can be achieved using fileno, dup and dup2 calls. I have tried this on linux not sure whether this will work on mac but I am sure you will get some equivalent functions for your setup. See if this sample code works for you. Sorry for lack of error-handling in the code. :)
#include <stdio.h>
main()
{
int fd;
fpos_t pos;
printf("stdout, ");
fflush(stdout);
fgetpos(stdout, &pos);
fd = dup(fileno(stdout));
freopen("stdout.out", "w", stdout);
f();
fflush(stdout);
dup2(fd, fileno(stdout));
close(fd);
clearerr(stdout);
fsetpos(stdout, &pos); /* for C9X */
printf("stdout again\n");
}
f()
{
printf("stdout in f()");
}
This seems like a roundabout way of solving your problem. Why not just open each file with fopen() and then writing to its FILE * with fputs, fprintf, fwrite etc? No need to redirect stdout.