今天遇到一个小题目是:编写一个程序将ps打印的内容输出到out文件中。
我们都知道exec函数组可以在程序内执行命令或程序,我用的是execlp这个函数。
重定向到out文件方面,使用dup2函数来实现。
函数的功能我就不在这啰嗦了,百度谷歌一搜一大把,也可以shell输入man+函数来查看具体用法。
上代码
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<fcntl.h>
int main(void){
int fd;
fd = open("./ps.out",O_WRONLY|O_TRUNC|O_CREAT,0644);
if(fd < 0){
perror("open error\n");
exit(1);
}
printf("fd = %d\n",fd);
dup2(fd,STDOUT_FILENO);
execlp("ps","ps","aux",NULL);
return 0;
}
哈哈,其实很简单,将ps.out文件描述符更改为标准输出文件描述符STDOUT_FILENO,这样原本调用execlp函数输出在屏幕上的内容就输出在ps.out文件里了/