in C
i want to redirect the output of a process from stdout to write to a "shared memory segment" which can be thought of as a char array or a string with a pointer
i know that there is dup2 but it takes file discriptors as argument not a pointer to an array. is there any way to redirect it to a string?
Asked
Active
Viewed 1.7k times
6
5 Answers
7
char string[SIZE];
freopen("/dev/null", "a", stdout);
setbuf(stdout, string);

sr01853
- 6,043
- 1
- 19
- 39
-
1Note that the buffer size MUST be exactly `BUFSIZ` in bytes! If it's smaller, you'll have a buffer overflow vulnerability, and if it's larger, it will never be used. This solution will not work if you want to buffer more than BUFSIZ bytes. – Vladimir Panteleev Apr 24 '14 at 13:23
-
2how to undo this ? Is it need to undo it ? – kangear Jan 18 '15 at 07:12
-
Windows equivalent please? – Unknown123 Oct 16 '22 at 17:56
-
@Unknown123 Replace on line 2 `freopen("/dev/null", "a", stdout);` with `freopen("nul", "a", stdout);` – FFmpegEnthusiast Aug 24 '23 at 06:50
3
This should work on UNIX systems:
// set buffer size, SIZE
SIZE = 255;
char buffer[SIZE];
freopen("/dev/null", "a", stdout);
setbuf(stdout, buffer);
printf("This will be stored in the buffer");
freopen ("/dev/tty", "a", stdout);

setnoset
- 249
- 3
- 7
-
Thanks, searched for ages trying to find how to do this. A few points !) requires c99 or later, 2) I had to set buffer[SIZE]={0} to avoid trailing garbage and 3) also works on Windows if you replace "/dev/tty" with "CON". – NoComprende Jan 17 '22 at 16:11
0
You could write to a pipe, and read from it into shared memory (that is, if you can't use the pipe instead of the string in shared memory).

NPE
- 486,780
- 108
- 951
- 1,012
-
i have two different processes (not a child and a parent) so i cant do pipe between them. right? – CSawy Jan 20 '13 at 21:04
0
with shm_open you can have a file descriptor pointing to a shared memory and pass it to dup2 function as below:
int fd = shm_open("shm-name", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR);
dup2(fd, STDOUT_FILENO);
fprintf(stdout, "This is string is gonna be printed on shared memory");
And after all seek the shared memory to the beginning (with lseek read it and save it to a string; But be careful
Also you can find an example of buffering into pipe in Here

pouyan
- 307
- 1
- 5
0
In order to do a simple redirection of stdout to a memory string, just do this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define PATH_MAX 1000
int main()
{
FILE *fp;
int status;
char path[PATH_MAX];
fp = popen("ls ", "r");
if (fp == NULL) return 0;
while (fgets(path, PATH_MAX, fp) != NULL)
printf("\nTest=> %s", path);
status = pclose(fp);
}