草庐IT

c++ - 向其他进程发送消息

coder 2024-06-20 原文

for (int i = 0; i < n; i++)
{
    const char* cstr = strings[i].c_str();
    swprintf_s(fullCommandLine, L"\"%s\" \"%s\" %S", pathToModule, pathToFile, cstr);
    if(CreateProcess(NULL,
        (LPWSTR)fullCommandLine,
        NULL,
        NULL,
        FALSE,
        0,
        NULL,
        NULL,
        &si,
        &pi))
    {
        cout << "succes";
    }
    else cout << "fail";
}

我正在创建 n 个进程来像这样在给定的文件中查找字符串,并且在我的模块中(wchich 在文件中查找给定的字符串)我想向其他 n-1 个进程发送消息以退出

while (file >> readout)
{
    if (readout == search)
    {
        cout << "I found string";
        SendMessage(/*what should be here*/);
    }
}

我从哪里可以获得那些其他进程的句柄?

最佳答案

请看我的PostThreadMessage to Console Application .

我创建它是因为肯定可以向控制台程序发送消息,我们只需要创建一个消息循环,就像可以从控制台程序显示一个窗口一样。

注意 PostThreadMessage 需要一个线程 id,而不是进程 id。每个进程也有一个线程 ID,进程的线程 ID 在 CreateProcess 的 PROCESS_INFORMATION 中。

以下是一个更大但更易于使用的示例,用于演示 PostThreadMessage 在控制台程序中的工作。如果没有参数,该程序将调用自身(传递其线程 ID),然后它将等待新进程发送消息。如果有一个参数,那么它将假定该参数是一个线程 ID,并向该线程发送一条消息,然后是一个 WM_QUIT。

#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
    TCHAR szCmdline[300];
    PROCESS_INFORMATION piProcInfo;
    STARTUPINFO siStartInfo;
    BOOL bSuccess = FALSE;

    ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION));
    ZeroMemory(&siStartInfo, sizeof(STARTUPINFO));
    siStartInfo.cb = sizeof(STARTUPINFO);
    siStartInfo.hStdError = NULL;
    siStartInfo.hStdOutput = NULL;
    siStartInfo.hStdInput = NULL;

    DWORD dwThread;
    MSG Msg;
    TCHAR ThreadIdBuffer[40];

    // if no argument then execute ourself then wait for a message from that thread
    if (argc == 1) {
        _itot_s(GetCurrentThreadId(), ThreadIdBuffer, 40, 10);
        szCmdline[0] = '"';
        szCmdline[1] = 0;
        _tcscat_s(szCmdline, 300, argv[0]); // ourself
        int n = _tcslen(szCmdline);
        szCmdline[n++] = '"';
        szCmdline[n++] = ' ';
        szCmdline[n++] = 0;
        _tcscat_s(szCmdline, 300, ThreadIdBuffer);  // our thread id
        bSuccess = CreateProcess(argv[0], // execute ourself
            szCmdline,     // command line
            NULL,          // process security attributes 
            NULL,          // primary thread security attributes 
            TRUE,          // handles are inherited 
            0,             // creation flags 
            NULL,          // use parent's environment 
            NULL,          // use parent's current directory 
            &siStartInfo,  // STARTUPINFO pointer 
            &piProcInfo);  // receives PROCESS_INFORMATION 
        if (!bSuccess) {
            std::cout << "Process not started\n";
            return 0;
            }
        std::cout << "Waiting\n";
        // Now wait for the other process to send us a message
        while (GetMessage(&Msg, NULL, 0, WM_USER)) {
            if (Msg.message == WM_COMMAND)
                std::cout << "WM_COMMAND\n";
            else
                std::cout << "Message: " << Msg.message << '\n';
        }
        std::cout << "End of message loop\n";
        return 0;
    }

    // if there is an argument then assume it is a threadid of another one of us
    std::cout << "Press Enter to send the message\n";
    if (std::wcin.get() != '\n')
        return 0;
    dwThread = _wtoi(argv[1]);
    if (!PostThreadMessage(dwThread, WM_COMMAND, (WPARAM)0, (LPARAM)0))
        std::cout << GetLastError() << " PostThreadMessage error\n";
    if (!PostThreadMessage(dwThread, WM_QUIT, (WPARAM)0, (LPARAM)0))
        std::cout << GetLastError() << " PostThreadMessage error\n";
    return 0;
}

关于c++ - 向其他进程发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36677559/

有关c++ - 向其他进程发送消息的更多相关文章

  1. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  2. ruby - 在 jRuby 中使用 'fork' 生成进程的替代方案? - 2

    在MRIRuby中我可以这样做:deftransferinternal_server=self.init_serverpid=forkdointernal_server.runend#Maketheserverprocessrunindependently.Process.detach(pid)internal_client=self.init_client#Dootherstuffwithconnectingtointernal_server...internal_client.post('somedata')ensure#KillserverProcess.kill('KILL',

  3. ruby - 通过 ruby​​ 进程共享变量 - 2

    我正在编写一个gem,我必须在其中fork两个启动两个webrick服务器的进程。我想通过基类的类方法启动这个服务器,因为应该只有这两个服务器在运行,而不是多个。在运行时,我想调用这两个服务器上的一些方法来更改变量。我的问题是,我无法通过基类的类方法访问fork的实例变量。此外,我不能在我的基类中使用线程,因为在幕后我正在使用另一个不是线程安全的库。所以我必须将每个服务器派生到它自己的进程。我用类变量试过了,比如@@server。但是当我试图通过基类访问这个变量时,它是nil。我读到在Ruby中不可能在分支之间共享类变量,对吗?那么,还有其他解决办法吗?我考虑过使用单例,但我不确定这是

  4. ruby-on-rails - 如何在 Rails View 上显示错误消息? - 2

    我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c

  5. jquery - 我的 jquery AJAX POST 请求无需发送 Authenticity Token (Rails) - 2

    rails中是否有任何规定允许站点的所有AJAXPOST请求在没有authenticity_token的情况下通过?我有一个调用Controller方法的JqueryPOSTajax调用,但我没有在其中放置任何真实性代码,但调用成功。我的ApplicationController确实有'request_forgery_protection'并且我已经改变了config.action_controller.consider_all_requests_local在我的environments/development.rb中为false我还搜索了我的代码以确保我没有重载ajaxSend来发送

  6. ruby - 使用 Ruby 通过 Outlook 发送消息的最简单方法是什么? - 2

    我的工作要求我为某些测试自动生成电子邮件。我一直在四处寻找,但未能找到可以快速实现的合理解决方案。它需要在outlook而不是其他邮件服务器中,因为我们有一些奇怪的身份验证规则,我们需要保存草稿而不是仅仅发送邮件的选项。显然win32ole可以做到这一点,但我找不到任何相当简单的例子。 最佳答案 假设存储了Outlook凭据并且您设置为自动登录到Outlook,WIN32OLE可以很好地完成此操作:require'win32ole'outlook=WIN32OLE.new('Outlook.Application')message=

  7. Ruby - 如何将消息长度表示为 2 个二进制字节 - 2

    我正在使用Ruby,我正在与一个网络端点通信,该端点在发送消息本身之前需要格式化“header”。header中的第一个字段必须是消息长度,它被定义为网络字节顺序中的2二进制字节消息长度。比如我的消息长度是1024。如何将1024表示为二进制双字节? 最佳答案 Ruby(以及Perl和Python等)中字节整理的标准工具是pack和unpack。ruby的packisinArray.您的长度应该是两个字节长,并且按网络字节顺序排列,这听起来像是n格式说明符的工作:n|Integer|16-bitunsigned,network(bi

  8. ruby - 使用 `+=` 和 `send` 方法 - 2

    如何将send与+=一起使用?a=20;a.send"+=",10undefinedmethod`+='for20:Fixnuma=20;a+=10=>30 最佳答案 恐怕你不能。+=不是方法,而是语法糖。参见http://www.ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html它说Incommonwithmanyotherlanguages,Rubyhasasyntacticshortcut:a=a+2maybewrittenasa+=2.你能做的最好的事情是:

  9. ruby-on-rails - 在 Flash 警报 Rails 3 中显示错误消息 - 2

    如果我在模型中设置验证消息validates:name,:presence=>{:message=>'Thenamecantbeblank.'}我如何让该消息显示在闪光警报中,这是我迄今为止尝试过的方法defcreate@message=Message.new(params[:message])if@message.valid?ContactMailer.send_mail(@message).deliverredirect_to(root_path,:notice=>"Thanksforyourmessage,Iwillbeintouchsoon")elseflash[:error]

  10. ruby - 如何计算 Liquid 中的变量 +1 - 2

    我对如何计算通过{%assignvar=0%}赋值的变量加一完全感到困惑。这应该是最简单的任务。到目前为止,这是我尝试过的:{%assignamount=0%}{%forvariantinproduct.variants%}{%assignamount=amount+1%}{%endfor%}Amount:{{amount}}结果总是0。也许我忽略了一些明显的东西。也许有更好的方法。我想要存档的只是获取运行的迭代次数。 最佳答案 因为{{incrementamount}}将输出您的变量值并且不会影响{%assign%}定义的变量,我

随机推荐