#include <unistd.h>
int dup(int fd);
int dup2(int fd, int fd2);
这两个函数可用来复制现有的文件描述符。
成功返回文件描述符,出错返回-1
dup返回当前可用文件描述符中的最小数值。
dup2中,fd2指定新的文件描述符,如果fd2已经打开,先将其关闭;如果fd等于fd2,返回fd2,不关闭。
例:利用子进程实现输出重定向
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
int main() {
int fd;
if ((fd = open("1.txt", O_RDWR | O_CREAT, 0644)) == -1) {
perror("open error");
exit(-1);
}
pid_t pid;
pid = fork();
if (pid<0) {
perror("fork error");
exit(-1);
}
else if (pid == 0) {
dup2(fd, 1);
execlp("ps", "ps", "-aux", NULL);
perror("exec error");
exit(-1);
//close(fd);
}
else sleep(1);
return 0;
}
不需要加close(fd),子进程结束后,打开的文件会被关闭。
成功执行完exec函数后,子进程就会结束,只有失败才会继续执行exec函数以后的语句。