fcntl设置文件为close_on_exec

来源:互联网 发布:android 移动网络 编辑:程序博客网 时间:2024/06/05 20:25

用于设置文件描述符fd的标志位,目前只有FD_CLOEXEC可以设置。默认情况下,该标志位为0,表示在使用exec加载的子进程中仍然可以保持文件描述符是打开的,否则在子进程中文件描述符被关闭。

在下面的代码中,close_on_exec是主进程,并fork一个子进程。通过fcnt F_SETFD设置文件描述符能否被共享。

如果该标识位打上,在子进程中write时报错:in child write: Bad file descriptor。否则在子进程中也是可以操作该描述符的。

Note:在Ubuntu中,使用open来创建一个不存在的文件,文件的权限总是很奇怪。直接执行close_on_exec创建的文件是只读的。如下。所以还得手动修改文件的权限。

-r----x--t 1 jincheng jincheng   24 2011-05-07 09:30 test.txt

 #include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>

int main()
{
    pid_t pid ;
    int fd ;
    int err = 0 ;
    char *stra = "aaaaaaaaaaa/n" ;
    char *strb = "bbbbbbbbbbb/n" ;

    fd = open("test.txt", O_RDWR|O_APPEND|O_CREAT, 777) ;
    if(fd == -1)
    {
        perror("open test.txt") ;
        return -1 ;
    }
    printf("fd=%d/n", fd) ;
    fcntl(fd, F_SETFD, 1) ;
    write(fd, (void*)stra, strlen(stra)) ;
    pid = fork() ;
    if(pid > 0)
    {
        printf("this is parent process/n") ;
        err = execl("child_aaa", "./child_aaa", &fd, NULL) ;
    }    
    else
    {
        write(fd, (void*)strb, strlen(strb)) ;
        wait(NULL) ;
    }
    close(fd) ;
}

 

#include <stdio.h>
#include <string.h>

int main(int argc, char* argv[])
{
    int fd ;
    int err = 0 ;
    if(argc != 2)
    {
        printf("error/n") ;
        return 0 ;
    }
    fd = *argv[1] ;
    printf("child fd=%d/n", fd) ;
    char *s = "ssssssssssss/n" ;
    err = write(fd, s, strlen(s)) ;
    if(err < 0)
    {
        perror("in child write") ;
        return -1 ;
    }
    close(fd) ;
    return 0 ;    
}

 

 

0 0