fcntl设置FD_CLOEXEC标志作用
2015-07-12 22:12
363 查看
通过fcntl设置FD_CLOEXEC标志有什么用?
close on exec, not on-fork, 意为如果对描述符设置了FD_CLOEXEC,使用execl执行的程序里,此描述符被关闭,不能再使用它,但是在使用fork调用的子进程中,此描述符并不关闭,仍可使用。
运行结果:
jamie@jamie-laptop:~$ cat wo.txt
this is a test
jamie@jamie-laptop:~$ ./test1
3
child, bytes:1,t //子进程中可使用fd
exe1: read fail:: Bad file descriptor //execl调用的程序中不能使用fd
parent, bytes:14,his is a test //父进程中当然能使用fd
close on exec, not on-fork, 意为如果对描述符设置了FD_CLOEXEC,使用execl执行的程序里,此描述符被关闭,不能再使用它,但是在使用fork调用的子进程中,此描述符并不关闭,仍可使用。
//test1.c #include <fcntl.h> #include <unistd.h> #include <stdio.h> #include <string.h> int main(void) { int fd,pid; char buffer[20]; fd=open("wo.txt",O_RDONLY); printf("%d\n",fd); int val=fcntl(fd,F_GETFD); val|=FD_CLOEXEC; fcntl(fd,F_SETFD,val); pid=fork(); if(pid==0) { //子进程中,此描述符并不关闭,仍可使用 char child_buf[2]; memset(child_buf,0,sizeof(child_buf) ); ssize_t bytes = read(fd,child_buf,sizeof(child_buf)-1 ); printf("child, bytes:%d,%s\n\n",bytes,child_buf); //execl执行的程序里,此描述符被关闭,不能再使用它 char fd_str[5]; memset(fd_str,0,sizeof(fd_str)); sprintf(fd_str,"%d",fd); int ret = execl("./exe1","exe1",fd_str,NULL); if(-1 == ret) perror("ececl fail:"); } waitpid(pid,NULL,0); memset(buffer,0,sizeof(buffer) ); ssize_t bytes = read(fd,buffer,sizeof(buffer)-1 ); printf("parent, bytes:%d,%s\n\n",bytes,buffer); }
//exe1.c #include <fcntl.h> #include <stdio.h> #include <assert.h> #include <string.h> int main(int argc, char **args) { char buffer[20]; int fd = atoi(args[1]); memset(buffer,0,sizeof(buffer) ); ssize_t bytes = read(fd,buffer,sizeof(buffer)-1); if(bytes < 0) { perror("exe1: read fail:"); return -1; } else { printf("exe1: read %d,%s\n\n",bytes,buffer); } return 0; }
运行结果:
jamie@jamie-laptop:~$ cat wo.txt
this is a test
jamie@jamie-laptop:~$ ./test1
3
child, bytes:1,t //子进程中可使用fd
exe1: read fail:: Bad file descriptor //execl调用的程序中不能使用fd
parent, bytes:14,his is a test //父进程中当然能使用fd
相关文章推荐
- Unity5.1 新的网络引擎UNET(四) UNET Remote Actions
- 如何将 Font Awesome 转成 PNG 图标 详细教程 含源代码
- 第一百零一天 how can i 坚持
- centos6系列(包括6.6)禁用IPV6
- LeetCode题解——3Sum
- 1133搜索(三)
- apache的开源项目-模板引擎(Velocity)_学习了两天就上手啦_源码下载
- 左旋转字符串
- Unity5.1 新的网络引擎UNET(三) UNET NetworkManager
- Linux 二进制包安装MySQL的一些问题
- 蓝牙
- codeforces 534B Covered Path-思维
- mysql中的事务回滚
- Unity5.1 新的网络引擎UNET(一) 概括2
- canvas加载图像
- The import javax.servlet.http.HttpServletRequest cannot be resolved
- JAVA大数处理(BigInteger,BigDecimal)
- Unity5.1 新的网络引擎UNET(七) UNET 单人游戏转换为多人
- 算法三之归并排序
- 使用Genymotion调试出现错误INSTALL_FAILED_CPU_ABI_INCOMPATIBLE解决办法