dup2函数

将当前系统中的进程信息打印到文件中

命令行:ps aux > out 将ps得到的信息重定向到out文件中

使用dup2文件在程序中完成。

int dup2(int oldfd,int newfd);
/***
dup2.c
***/
#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdlib.h>

int main()
{
    int fd;
    
    fd = open("ps.out",O_WRONLY|O_CREAT|O_TRUNC,0644);
    if(fd < 0)
    {
        perror("open ps.out error");
        exit(1);
    }
    dup2(fd,STDOUT_FILENO); //dup2(3,1);  fd,stdout
    execlp("ps","ps","ax",NULL);
    //close(fd);
    return 0;
}

运行结果:

ubuntu1604@ubuntu:~/wangqinghe/linux/20190806$ ls -l ps.out

-rw-r--r-- 1 ubuntu1604 ubuntu1604 13121 8月   6 14:00 ps.out

原文地址:https://www.cnblogs.com/wanghao-boke/p/11311790.html