如何保存execvp输出 [英] How to save execvp output

查看:433
本文介绍了如何保存execvp输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在保存execvp输出时遇到问题.我想将(ps -eo pid,fname,state,ppid,gid,sid)的输出保存在txt文件中.

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 .

这是我的代码:

#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 .

推荐答案

由于您是通过直接调用execvp来清除进程的,因此只需将输出重定向到文件即可:

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

这篇关于如何保存execvp输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆