利用dup2重定向,把ps ax的输出打印到ps.out文件中。
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<fcntl.h>
#include<sys/types.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);//重定向stdout到fd指向的文件
execlp("ps","ps","ax",NULL);
printf("hello");
perror("exec error");
exit(1);
return 0;
}