執行個體程式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//這個時候,會列印錯誤資訊到标準錯誤輸出