2

I have problem with saving the execvp output.I want to save the output of (ps -eo pid,fname,state,ppid,gid,sid) in txt file .

This is my code :

#include <unistd.h>

int main(void)
{   
    char* args[]={"ps","-eo","pid,fname,state,ppid,gid,sid" , ">" , "t.txt"};
    execvp(args[0],args);

    return 0;
}

But when i run it .It doesnt work .

dragosht
  • 3,237
  • 2
  • 23
  • 32
  • 1
    *Fork* a new process, and have a *pipe* to transfer the output from the standard output to your parent process. There are thousands of examples of this all over the Internet if you just search a little. – Some programmer dude Oct 26 '15 at 11:52
  • 1
    By the way, your argument array is not terminated, calling `execvp` will lead to undefined behavior when it goes beyond the end of the array to find the terminator. – Some programmer dude Oct 26 '15 at 11:52
  • 1
    Perhaps consider using [popen(3)](http://man7.org/linux/man-pages/man3/popen.3.html) or directly use  [proc(5)](http://man7.org/linux/man-pages/man5/proc.5.html) – Basile Starynkevitch Oct 26 '15 at 11:54

2 Answers2

3

Since you're wiping out your process by directly calling execvp, you could simply redirect the output to your file:

int main()
{
    char * args[] = {"ps","-eo","pid,fname,state,ppid,gid,sid", 0};
    int fd = open("t.txt", O_CREAT | O_TRUNC | O_RDWR, 0644);
    if (fd < 0) {
        perror("open()");
        exit(EXIT_FAILURE);
    }
    close(STDOUT_FILENO);

    dup2(fd, STDOUT_FILENO);

    execvp(args[0], args);

    return 0;
}
dragosht
  • 3,237
  • 2
  • 23
  • 32
0

">" (stream redirection) is supported by shell, so here you actually need run shell with arguments of ps stuff.

Popen is just a way that redirect stream in a more controlled way.

Sam Liao
  • 43,637
  • 15
  • 53
  • 61