fcntl
//fcntl.c
#include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <stdio.h> #include <string.h> int set_fd(int); int main() { int fd,ret; char f[20]; fd=open("pighead.txt",O_RDWR|O_CREAT); set_fd(fd); sprintf(f,"%d",fd); ret=execl("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;
//flag|=FD_CLOEXEC; fcntl(fd,F_SETFD,flag); return 0; }
// test.c #include <stdlib.h> #include <unistd.h> #include <fcntl.h> #include <stdio.h> #include <string.h> int main(int argc,char **argv) { int fd,ret; system("echo abc >te.log"); printf("argv[0]:%s, argv[1]:%s\n",argv[0],argv[1]); fd=atoi(argv[0]); char str[16]; strcpy(str,"hello,world~\n"); printf("%s",str); ret=write(fd,str,strlen(str)); printf("ret:%d\n",ret); return 0; }
mutian@mutian:~/Downloads/temp/test$ ls
fcntl.c test.c
mutian@mutian:~/Downloads/temp/test$ g++ -o fcntl fcntl.c
mutian@mutian:~/Downloads/temp/test$ g++ -o test test.c
mutian@mutian:~/Downloads/temp/test$
mutian@mutian:~/Downloads/temp/test$
mutian@mutian:~/Downloads/temp/test$ ./fcntl
argv[0]:3, argv[1]:(null)
hello,world~
ret:13
mutian@mutian:~/Downloads/temp/test$ ls
fcntl fcntl.c pighead.txt te.log test test.c
mutian@mutian:~/Downloads/temp/test$ cat pighead.txt
hello,world~
mutian@mutian:~/Downloads/temp/test$ cat te.log
abc
mutian@mutian:~/Downloads/temp/test$ rm pighead.txt te.log
mutian@mutian:~/Downloads/temp/test$ vi fcntl.c
//修改代码后
mutian@mutian:~/Downloads/temp/test$ g++ -o fcntl fcntl.c
mutian@mutian:~/Downloads/temp/test$ ./fcntl
argv[0]:3, argv[1]:(null)
hello,world~
ret:-1
mutian@mutian:~/Downloads/temp/test$ ls
fcntl fcntl.c pighead.txt te.log test test.c
mutian@mutian:~/Downloads/temp/test$ cat pighead.txt //由于关闭了fd, 所以这里内容写不进去
mutian@mutian:~/Downloads/temp/test$ cat te.log
abc
mutian@mutian:~/Downloads/temp/test$

浙公网安备 33010602011771号