【问题标题】:how to pass integer value between 2 process in c如何在c中的2个进程之间传递整数值
【发布时间】:2015-04-05 15:51:54
【问题描述】:

如何在 2 个进程之间传递整数值?

例如:
我有 2 个进程:child1 和 child2。 Child1 向 child2 发送一个整数。 Child2 然后将该值乘以 2 并将其发送回 child1。然后子 1 将显示该值。

如何在 Windows 平台上使用 C 语言执行此操作?有人可以提供一个代码示例来说明如何做到这一点吗?

【问题讨论】:

  • 您可以使用管道。此链接可能会有所帮助 - stackoverflow.com/questions/12864265/…
  • 如何使用书面文本将信息传递给读者:使用大写字母开始句子。使用句号结束​​句子.
  • @alk 对不起。下次我会更小心的
  • @Razib 谢谢。但是当运行你给我的链接中的代码时,我得到了这个错误:“(.text+0x3a): undefined reference to `pipe'”。你知道我该如何解决它吗?
  • 你描述的是IPC,是通用和广泛的。

标签: c


【解决方案1】:

IPC(或Inter-process communication)确实是一个广泛的主题。
您可以使用共享文件、共享内存或信号等等。
使用哪一个完全取决于您,并由您的应用程序设计决定。

既然你写了你正在使用 Windows,这里有一个使用管道的工作示例:

请注意,我将缓冲区视为以空字符结尾的字符串。您可以将其视为数字。

服务器:

// Server
#include <stdio.h>
#include <Windows.h>

#define BUFSIZE     (512)
#define PIPENAME    "\\\\.\\pipe\\popeye"

int main(int argc, char **argv)
{
    char msg[] = "You too!";
    char buffer[BUFSIZE];
    DWORD dwNumberOfBytes;
    BOOL bRet = FALSE;
    HANDLE hPipe = INVALID_HANDLE_VALUE;

    hPipe = CreateNamedPipeA(PIPENAME,
        PIPE_ACCESS_DUPLEX,
        PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
        PIPE_UNLIMITED_INSTANCES,
        BUFSIZE,
        BUFSIZE,
        0,
        NULL);

    bRet = ConnectNamedPipe(hPipe, NULL);

    bRet = ReadFile(hPipe, buffer, BUFSIZE, &dwNumberOfBytes, NULL);
    printf("receiving: %s\n", buffer);

    bRet = WriteFile(hPipe, msg, strlen(msg)+1, &dwNumberOfBytes, NULL);
    printf("sending: %s\n", msg);

    CloseHandle(hPipe);

    return 0;
}

客户:

// client
#include <stdio.h>
#include <Windows.h>

#define BUFSIZE     (512)
#define PIPENAME    "\\\\.\\pipe\\popeye"

int main(int argc, char **argv)
{
    char msg[] = "You're awesome!";
    char buffer[BUFSIZE];
    DWORD dwNumberOfBytes;

    printf("sending: %s\n", msg);
    CallNamedPipeA(PIPENAME, msg, strlen(msg)+1, buffer, BUFSIZE, &dwNumberOfBytes, NMPWAIT_WAIT_FOREVER);
    printf("receiving: %s\n", buffer);

    return 0;
}

希望有帮助!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多