天天看點

檔案描述符和exec的關系

檔案描述符和exec的關系

  • 預設情況下,由exec()調用程序打開的檔案描述符,在exec()執行過程中,甚至執行結束之後的新程式中,都是有效不變的
  • close-on-exec标志(FD_CLOEXEC):核心為每個檔案描述符提供了執行時關閉标志,當exec()執行成功之後,會自動關閉設定了FD_CLOEXEC标志的檔案描述符,如果exec()調用失敗,檔案描述符依然會保持打開狀态
  • 執行個體程式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//這個時候,會列印錯誤資訊到标準錯誤輸出
               

繼續閱讀