簡體   English   中英

c sendfile第二次不起作用

[英]c sendfile doesn't works the 2nd time

這是LIST ftp的cmd的代碼段:

count = file_list("./", &files);
if((fp_list = fopen("listfiles.txt", "w")) == NULL){
  perror("Impossibile aprire il file per la scrittura LIST");
  onexit(newsockd, sockd, 0, 2);
}
for(i=0; i < count; i++){
  if(strcmp(files[i], "DIR ..") == 0 || strcmp(files[i], "DIR .") == 0) continue;
  else{
    fprintf(fp_list, "%s\n", files[i]);
  }
}
fclose(fp_list);
if((fpl = open("listfiles.txt", O_RDONLY)) < 0){
  perror("open file with open");
  onexit(newsockd, sockd, 0, 2);
  exit(1);
}
if(fstat(fpl, &fileStat) < 0){
  perror("Errore fstat");
  onexit(newsockd, sockd, fpl, 3);
}
fsize = fileStat.st_size;
if(send(newsockd, &fsize, sizeof(fsize), 0) < 0){
  perror("Errore durante l'invio grande file list");
  onexit(newsockd, sockd, fpl, 3);
}
rc_list = sendfile(newsockd, fpl, &offset_list, fileStat.st_size);
if(rc_list == -1){
  perror("Invio file list non riuscito");
  onexit(newsockd, sockd, fpl, 3);
}
if((uint32_t)rc_list != fsize){
  fprintf(stderr, "Error: transfer incomplete: %d di %d bytes inviati\n", rc_list, (int)fileStat.st_size);
  onexit(newsockd, sockd, fpl, 3);
}
printf("OK\n");
close(fpl);
if(remove( "listfiles.txt" ) == -1 ){
  perror("errore cancellazione file");
  onexit(newsockd, sockd, 0, 2);
}

&files被聲明為char **files ,函數list_files是我編寫的與我的問題無關的函數。
我的問題:第一次使用LIST cmd可以正常工作,但是如果我再次調用LIST,它總是給我“錯誤,傳輸不完整”,我不明白為什么...

sendfile函數可能不會在一個調用中發送所有數據,在這種情況下,它將返回小於請求的數字。 您將其視為錯誤,但應重新嘗試。 一種方法是使用類似於以下的循環:

// Offset into buffer, this is where sendfile starts reading the buffer
off_t offset = 0;

// Loop while there's still some data to send
for (size_t size_to_send = fsize; size_to_send > 0; )
{
    ssize_t sent = sendfile(newsockd, fpl, &offset, size_to_send);

    if (sent <= 0)
    {
        // Error or end of file
        if (sent != 0)
            perror("sendfile");  // Was an error, report it
        break;
    }

    size_to_send -= sent;  // Decrease the length to send by the amount actually sent
}

我發現了我的問題。
當我多次調用sendfile變量off_t offset_list; 仍然“骯臟”
如果調用sendfile,則第一次offest_list的值將不會被第二次調用該函數刪除。
因此,如果我必須寫offset_list = 0; rc_list = sendfile(newsockd, fpl, &offset_list, fileStat.st_size); 和所有的工作!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM