將當前系統中的進程信息打印到文件中
命令行: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,stdoutexeclp("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