续fcntl()之F_SETFD,F_GETFD

上文书说到对于这两个参数还没有搞定是如何用的,结果斗胆在CU发了一个帖子,
终于弄明白了~~
 

[root@FC5 tmp]# cat fcntl.c
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
int set_fd(int);
int main()
{
        int fd,ret;
        char f[20];
        fd=open("/tmp/pighead.txt",O_RDWR|O_CREAT);
        set_fd(fd);
        sprintf(f,"%d",fd);
        ret=execl("/tmp/test",f,(char *)0);
        printf("ret:%d/n",ret);
        return 0;
}

int set_fd(int fd)
{
        unsigned int flag;
        flag=fcntl(fd,F_GETFD);
        flag|=~FD_CLOEXEC; //去掉'~'看看
        fcntl(fd,F_SETFD,flag);
        return 0;
}
[root@FC5 tmp]# cat test.c
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
int main(int argc,char **argv)
{
int fd,ret;
system("echo abc >te.log");
printf("%s:argv[1]:%s/n",argv[0],argv[1]);
fd=atoi(argv[0]);
char str[16];
strcpy(str,"hello,world~/n");

printf("%s/n",str);
ret=write(fd,str,strlen(str));
printf("ret:%d/n",ret);
return 0;
}

 
结果

[root@FC5 tmp]# gcc -o test test.c
[root@FC5 tmp]# gcc -o fcnt fcntl.c
[root@FC5 tmp]# ls pighead.txt
ls: pighead.txt: No such file or directory
[root@FC5 tmp]# ./fcnt
3:argv[1]:(null)
hello,world~

ret:13
[root@FC5 tmp]# cat pighead.txt
hello,world~

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值