Chinaunix首页 | 论坛 | 博客
  • 博客访问: 3309739
  • 博文数量: 258
  • 博客积分: 9440
  • 博客等级: 少将
  • 技术积分: 6998
  • 用 户 组: 普通用户
  • 注册时间: 2009-05-03 10:28
个人简介

-- linux爱好者,业余时间热衷于分析linux内核源码 -- 目前主要研究云计算和虚拟化相关的技术,主要包括libvirt/qemu,openstack,opennebula架构和源码分析。 -- 第五届云计算大会演讲嘉宾 微博:@Marshal-Liu

文章分类

全部博文(258)

文章存档

2016年(1)

2015年(4)

2014年(16)

2013年(22)

2012年(41)

2011年(59)

2010年(40)

2009年(75)

分类: LINUX

2011-11-10 19:59:44

通过fcntl设置FD_CLOEXEC标志有什么用?
close on exec, not on-fork, 意为如果对描述符设置了FD_CLOEXEC,使用execl执行的程序里,此描述符被关闭,不能再使用它,但是在使用fork调用的子进程中,此描述符并不关闭,仍可使用。
eg:
jamie@jamie-laptop:~$ cat test.c
#include
#include
#include
#include

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);
}

jamie@jamie-laptop:~$ cat exe1.c
#include
#include
#include
#include

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:~$ gcc -o exe1 exe1.c
jamie@jamie-laptop:~$ gcc -o test test.c
jamie@jamie-laptop:~$ cat wo.txt
this is a test
jamie@jamie-laptop:~$ ./test
3
child, bytes:1,t                               //子进程中可使用fd

exe1: read fail:: Bad file descriptor  //execl调用的程序中不能使用fd
parent, bytes:14,his is a test          //父进程中当然能使用fd
阅读(3260) | 评论(1) | 转发(5) |
给主人留下些什么吧!~~

wlan02013-07-26 23:42:46

博主,printf函数中的反斜杠好像用错了哦。。。