windows系統調用 利用事件對象實現進程通訊

來源:互聯網
上載者:User

標籤:style   class   blog   code   tar   color   

 1 #include "iostream" 2 #include "windows.h" 3 #include "cstring" 4 using namespace std; 5  6 static LPCTSTR g_szContinueEvent="w2kdg.EventDemo.event.Continue"; 7  8 BOOL CreateChild(){ 9     TCHAR szFilename[MAX_PATH];10     GetModuleFileName(NULL,szFilename,MAX_PATH);11 12     TCHAR szCmdLine[MAX_PATH];13     sprintf_s(szCmdLine,"\"%s\" child",szFilename);14 15     STARTUPINFO si;16     ZeroMemory(reinterpret_cast<void*>(&si),sizeof(si));17     si.cb=sizeof(si);18 19     PROCESS_INFORMATION pi;20 21     BOOL bCreateOK=CreateProcess(22         szFilename,23         szCmdLine,24         NULL,25         NULL,26         FALSE,27         0,28         NULL,29         NULL,30         &si,31         &pi32         33         );34 35     if(bCreateOK){36         CloseHandle(pi.hProcess);37         CloseHandle(pi.hThread);38     }39 40     return (bCreateOK);41 42 }43 44 void WaitForChild(){45     HANDLE hEventContinue=CreateEvent(46         NULL,47         TRUE,48         FALSE,49         g_szContinueEvent50         );51 52     if(hEventContinue!=NULL){53         printf("Event creates.\n");54         if(CreateChild()){55             printf("Child process created.\n");56             printf("Parent process waiting on child process.\n");57             WaitForSingleObject(hEventContinue,INFINITE);58             printf("Parent process received the event signaling from child process.\n");59         }60 61         CloseHandle(hEventContinue);62     }63 64 }65 66 void SignalParent(){67     HANDLE hEventContinue=OpenEvent(68         EVENT_MODIFY_STATE,69         FALSE,70         g_szContinueEvent71         );72 73     if(hEventContinue!=NULL){74         SetEvent(hEventContinue);75         printf("Child process begining...\n");76     }77 78     CloseHandle(hEventContinue);79 }80 81 int main(int argc,char *argv[]){82     if(argc>1&&strcmp(argv[1],"child")==0){83         SignalParent();84     }85     else{86     87     WaitForChild();88     printf("Parent process released.\n");89     }90     getchar();91     return 0;92 93 }

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.