程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程綜合問答 >> linux c-關於使用 dup2 函數重定向的一些疑問,望高手解惑~~!!

linux c-關於使用 dup2 函數重定向的一些疑問,望高手解惑~~!!

編輯:編程綜合問答
關於使用 dup2 函數重定向的一些疑問,望高手解惑~~!!

先上一段正常的代碼,如下:

 #include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>


int main(){
    int oldfd = open("mytest",O_RDWR | O_CREAT,0644);

    dup2(oldfd,1);
  close(oldfd); 

  printf("hello world\n");
  return 0;

}

編譯,運行,結果正常, hello world 被重定向到了文件。
接著 給代碼 加上一個 死循環,讓 hello world 不斷的寫入重定向的文件。代碼如下:

 #include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>


int main(){
    int oldfd = open("mytest",O_RDWR | O_CREAT,0644);

    dup2(oldfd,1);
  close(oldfd); 

  while(1)
    printf("hello world\n");
  return 0;

}

編譯,運行,然後查看 mytest 文件,發現 hello world 在不斷的寫入,也是正常的。然後,加上一個 sleep 出現問題了。(先刪除 mytest 文件,然後修改代碼)。代碼如下:

 #include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>


int main(){
    int oldfd = open("mytest",O_RDWR | O_CREAT,0644);

    dup2(oldfd,1);
  close(oldfd); 

  while(1){
    sleep(1);
    printf("hello world\n");    
  }
  return 0;

}

這個時候再編譯運行,然後使用 cat 查看 mytest 文件,發現沒有內容。 ls -l 查看 發現文件大小為0

最佳回答:


我自己找到答案了,修改後的代碼如下:

``#include
#include
#include
#include
#include

int main(){
int oldfd = open("/home/gino/code/mytest",O_RDWR | O_CREAT,0644);

if(dup2(oldfd,1) == -1)
    printf("dup2 err\n");

close(oldfd);
while(1){
sleep(1);
printf("hello world!\n");

fflush(stdout);
}
return 0;
}`


原因是 stdout 在 中的數據並不會立刻輸出,而是要等待進程要關閉的時候在輸出,那麼加上 fflush 函數 清除讀寫緩沖區即可。
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved