文件描述符的复制

#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函数以后的语句。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值