user5329895
user5329895

Reputation:

How to capture the output of execvp() function in c?

I'm using execvp() function in C.
My code:

pid_t pid = fork();
 if(pid < 0)
            printf("Fork faild\n");
         else if(pid == 0)
         {
            // chirld process
         } 
         else
         {
            // parent process
            execvp(args[0],args) 
         }

with args variable is "ls". My screen display particular file such as

a.txt , b.c , c.pdf

....etc. So.. Can this function return to a variable? Such as:

char str[MAX] = " a.txt b.c c.pdf ";

Sorry my english is bad.

UPDATE

I need send result of execvp() function from server to client using send() , recv().

Upvotes: 0

Views: 2520

Answers (1)

Stas
Stas

Reputation: 11761

If it is enough to capture stdout, popen is a good git. It will create a pipe and will fork the process under the hood, so it is not needed to do it manually.

Simple example of popen usage:

#include <stdio.h>

int main(void)
{
        FILE* p = popen("ls -la", "r");
        if (!p) return 1;

        char buff[1024];
        while (fgets(buff, sizeof(buff), p)) {
                printf("%s", buff);
        }
        pclose(p);

        return 0;
}

Upvotes: 1

Related Questions