实例程序1: #include <stdbool.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
int flags;
if (argc > 1)
{
flags = fcntl(1, F_GETFD); //获取当前文件描述符的相关信息
flags |= FD_CLOEXEC; //加上标志FD_CLOEXEC
//fcntl(1, F_SETFD, flags); //为标准输出设置FD_CLOEXEC标志
}
execlp("ls", "ls", "-l", argv[1], (char *)NULL); //执行ls -l命令
return 0;
}
//输出结果
[email protected]:/home/farsight/c_test# ./16 test.log
-rw-r--r-- 1 root root 29 8月 27 00:31 test.log
//因为标准输出没有设置FD_CLOEXEC标志,当execlp用ls程序替代之后,标准输出依然处于打开状态,如果设置了FD_CLOEXEC标志,那么标准输出在execlp执行成功之后,会关闭,此时运行程序的结果如下:
[email protected]:/home/farsight/c_test# ./16 test.log
ls: write error: Bad file descriptor//这个时候,会打印错误信息到标准错误输出