How to save execvp output

安稳与你 提交于 2019-12-24 12:45:30

问题


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 .


回答1:


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;
}



回答2:


">" (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.



来源:https://stackoverflow.com/questions/33345025/how-to-save-execvp-output

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!