linux exec函数执行之前设置当前进程所有描述符FD_CLOEXEC

1、查看进程打开的描述符

ll /proc/$PID/fd

linux exec函数执行之前设置当前进程所有描述符FD_CLOEXEC_第1张图片

2、C语言获取当前进程打开的fd并设置FD_CLOEXEC

#include 
#include 
#include 
#include 
#include 
#include


/* 将当前进程打开的所有描述符标志设置为CLOEXEC */
static void SetFDFlagToCLOEXEC(char* fd_path)
{
    if(!fd_path)
        return;
    //fcntl(fd,F_SETFD,FD_CLOEXEC); /* 设置exec时关闭 */
    
    DIR *dir;
    struct dirent *ptr;
    if ((dir = opendir(fd_path)) == NULL)
    {
        perror("Open dir error...");
        cout << " opendir error " << strerror(errno);
        return;
    }

    int fd = 0;
    while ((ptr = readdir(dir)) != NULL)
    {
        if(strcmp(ptr->d_name,".")==0 || strcmp(ptr->d_name,"..")==0)
            continue;
        
        fd = atoi(ptr->d_name);
        //if(fd == 0 || fd == 1 || fd == 2)
        //{
        //    continue;
        //}
        
        if(ptr->d_type == 8)    ///file
        {
            cout << " FD is " << ptr->d_name;
            fcntl(fd, F_SETFD, FD_CLOEXEC);
        }
        else if(ptr->d_type == 10)    ///link file
        {
            LOG_DEBUG << " FD is " << ptr->d_name;
            int ret = 0;
            //int ret = fcntl(fd, F_GETFD, 0);
            //cout << " ret&FD_CLOEXEC " << (ret&FD_CLOEXEC);
            
            fcntl(fd, F_SETFD, FD_CLOEXEC);
            ret = fcntl(fd, F_GETFD, 0);
            if(ret&FD_CLOEXEC)
            {
                cout << "exec运行 时该描述符关闭";
            }
        }
        else if(ptr->d_type == 4)    ///dir
        {
           
        }
    }
    
    closedir(dir);
    
}

int main()
{
	pid_t pid = getpid();
    char fd_path[64];
    memset(fd_path, 0, 64);
    snprintf(fd_path, 64, "/proc/%d/fd", pid);
    
    if (access(fd_path, 0) == -1)
    {
       /* 文件夹不存在 */
    }
    else
    {
        SetFDFlagToCLOEXEC(fd_path);
    }
    
    execv("demo", NULL);
}

3、参考

《1》、linux 根据进程号查看进程打开的所有文件描述符

你可能感兴趣的:(linux编程,C/C++)