fcntl设置文件为close_on_exec

用于设置文件描述符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 ;   
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值