Zach Saucier
Zach Saucier

Reputation: 25994

Pass a string as standard input to an executable

I have count = read(pipe, buffer, buffsize); and am trying to run what is received (buffer) through another executable to have a differing process done on it.

printf("%s", buffer); prints it out correctly, but running it through execl("/path", "/path", buffer, NULL); or a number of other ways I've tried doesn't seem to run the executable. path is a compiled executable.

The executable does run properly if I use execv("./path", STDIN_FILENO);, but that isn't being taken from the pipe. path is expecting a the string as standard input.

The situation of the program is that I'm typing in input on one program using a while loop and read(), using a pipe to send that text to the program that is running execl (nothing else needs to be done in this program), that is then trying to call the executable with the string as an stdin. Only the intended input is coming in through the pipe, in chunks when the user presses enter.

An example of a string coming through the pipe is this is an example. The executable needs to have this inputted as standard input.

How can I get the string to be used as standard input for /path executable correctly?

Upvotes: 1

Views: 2255

Answers (1)

Crowman
Crowman

Reputation: 25936

It sounds like popen() is what you're looking for, to open a pipe to your desired executable so you can either pass stuff to its standard input, or read stuff from its standard output.

For instance:

#define _POSIX_C_SOURCE 200809L

#include <stdio.h>
#include <stdlib.h>

int main(void) {
    FILE * p = popen("/bin/cat", "w");
    if ( !p ) {
        perror("error opening pipe");
        return EXIT_FAILURE;
    }

    fputs("Echo me via /bin/cat\n", p);

    if ( pclose(p) == -1 ) {
        perror("error closing pipe");
        return EXIT_FAILURE;
    }

    return 0;
}

which outputs:

paul@thoth:~/src/sandbox$ ./testpopen
Echo me via /bin/cat
paul@thoth:~/src/sandbox$ 

Upvotes: 2

Related Questions