【问题标题】:Trying to write publisher-subscriber relation using IFC pipes, forking too many subscribers尝试使用 IFC 管道编写发布者-订阅者关系,分叉太多订阅者
【发布时间】:2014-11-26 22:01:49
【问题描述】:

我正在尝试编写一个程序,它分叉一个服务器进程、n 个发布者进程、m 个订阅者进程,为每个发布者和订阅者进程创建一个管道,并监听每个管道上的信息。我做了一些工作,但我不太清楚我需要做什么才能使我编写的代码完整。

绝对错误的一件事是分叉的订阅者进程远不止 m 个。为什么会发生这种情况,我该如何解决?

任何建议将不胜感激!

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>

int num_publishers = 0;
int num_subscribers = 0;

int main(int argc, char *argv[])
{
    int pfds[2];
    char buf[128];

    num_publishers = atoi(argv[1]);
    num_subscribers = atoi(argv[2]);
    printf("%d publishers and %d subscribers.\n", num_publishers, num_subscribers);

    pid_t pub_pids[num_publishers];
    pid_t sub_pids[num_subscribers];


    for (int i=0; i < num_publishers; i++)
    {
        pub_pids[i] = fork();
        printf("Publisher: %d \n", pub_pids[i]);
    }

    printf("\n");

    for (int i=0; i < num_subscribers; i++)
    {
        sub_pids[i] = fork();
        printf("Subscriber: %d \n", sub_pids[i]);
    }

    printf("\n");

    pipe(pfds);


    if (!fork())
    {
        printf("CHILD: writing to the pipe\n");
        write(pfds[1], );
        printf("CHILD: exiting\n");
        exit(0);
    }
    else
    {
        printf("PARENT: reading from pipe\n");
        read(pfds[0], buf, 5);
        printf("PARENT: read \"%s\"\n", buf);
        wait(NULL);
    }

    return 0;

}

【问题讨论】:

    标签: c process pipe fork publish-subscribe


    【解决方案1】:

    简答:你的父进程和你的子进程都在产生更多的子进程。

    fork() 返回两次 - 一次在父项中,一次在子项中。

    如果你是父母,你想记录孩子的pid并创建更多的孩子。

    如果你是孩子,你想去做一些工作。 (也许 exec() 一些其他可执行文件。)

    您可以根据 fork 的返回值来区分它们。

    所以:

    sub_pids[i] = fork();
    if (sub_pids[i] == 0) {
       /* child */
       ... get out of the loop here ...
    } else if (sub_pids[i] == -1) {
       /* error */
       ... report the error here ...
    } else {
       /* parent */
       ... nothing to do here, just continue the loop ...
    }
    

    [edit] 我看到你在代码 sn-p 的末尾确实有一个正确的 fork()。也许那部分需要变成一个子程序,从循环中调用。

    另外 - 您必须在分叉之前创建管道。在调用 pipe() 之前你有你的创建循环

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-14
      • 1970-01-01
      • 2021-07-28
      • 1970-01-01
      • 2016-08-11
      相关资源
      最近更新 更多