首页 > 其他 > 详细

dup2函数

时间:2019-08-06 21:50:54      阅读:151      评论:0      收藏:0      [点我收藏+]

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

命令行: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

dup2函数

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!