fcntl設置FD_CLOEXEC標誌作用

通過fcntl設置FD_CLOEXEC標誌有什麼用?

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

發佈了103 篇原創文章 · 獲贊 12 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章