close-on-exec标志的作用是使得文件描述符自动关闭,如果fork子进程之后子进程要执行exec*(),如果不设置close-on-exec标志会导致文件描述符没有关闭。
实例:parent.c
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
int main()
{
pid_t pid;
int fd = open("test.txt",O_RDWR|O_CREAT|O_APPEND);
if (fd == -1)
{
printf("open file error\n");
return -1;
}
printf("fd = %d\n",fd);
/*
int val = 0;
if((val = fcntl(fd,F_GETFD,0)) < 0)
{
printf("F_GETFL failed\n");
return -1;
}
val |= FD_CLOEXEC;
if(fcntl(fd, F_SETFD, FD_CLOEXEC) < 0)
{
printf("F_SETFD failed\n");
return -1;
}
*/
char *s="parentparentparentparent";
pid = fork();
/*子进程*/
if(pid == 0)
{
execl("child", "./child", &fd, NULL);
}
wait(NULL);
write(fd,s,strlen(s));
close(fd);
return 0;
}
实例:child.c
#include <stdio.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int fd;
fd = *argv[1];
printf("%d\n",fd);
char *s = "childchildchildchild";
if(write(fd, (void *)s, strlen(s)) != strlen(s))
{
printf("write error in child\n");
}
close(fd);
return 0;
}
执行:
gcc -g -o child child.c
gcc -g -o parent parent.c
./parent
打开和关闭parent.c中注释的内容,验证close-on-exec标志的作用。