Redirect output from stdout to string?

in C I want to redirect process output from stdout to write to a "shared memory segment", which can be thought of as a char array or a pointer line
I know there is dup2, but it takes file descriptors as an argument, not a pointer to an array. is there any way to redirect it to a string?

+4
source share
5 answers
char string[SIZE]; freopen("/dev/null", "a", stdout); setbuf(stdout, string); 

see freopen and setbuf for their definition

+4
source

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); 
+1
source

You can write to a pipe and read it into shared memory (that is, if you cannot use this channel instead of a line in shared memory).

0
source

with shm_open, you can have a file descriptor pointing to shared memory and pass it to dup2, as shown 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 in the end, find the shared memory at the beginning (use lseek to read it and save it in a line, but be careful

You can also find an example of pipe buffering in Here.

0
source

To do a simple redirection of stdout to a memory line, simply do the following:

 #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); } 
0
source

All Articles