C,使用pipe()在两个方向上与子进程通信

时间:2016-05-24 21:19:22

标签: c linux pipe

我正在尝试编写一个功能如下的程序:

  • 用户提供所需的子进程数量
  • 每个孩子都会生成一个随机数,并将其与相应的PID一起传递给父母。
  • 家长决定获胜者
  • 父级使用中奖号码
  • 填充缓冲区
  • 孩子们检查他们是否赢了
struct Data {
    int pid;
    int nummer;
};

int main(int argc, char ** argv) {

    int aantal = atoi(argv[1]);
    printf("Amount : %d \n", aantal);
    int j;
    int pids[aantal];
    int kinderen = 0;
    int i;
    int fd[2];
    int fd2[2];
    int winnaar = 0;
    int grootste = 0;
    int pid;

    for (i = 0; i < aantal; i++) {
        if (!(pipe(fd) > -1 || pipe(fd2) > -1)) {
            printf("Pipe error!");
            exit(0);
        }

        if ((pid = fork()) == 0) {
            srand(getpid());
            struct Data data;
            data.nummer = rand();
            data.pid = getpid();
            close(fd[0]);
            close(fd2[1]);
            printf("Try to send... \n");
            write(fd[1], (void * )( & data), sizeof(struct Data));
            printf("Sent! \n");

            int nummer;
            while ((read(fd2[0], (void * )( & nummer), sizeof(int))) != sizeof(int));
            printf("Received %d \n", nummer);

            if (nummer == getpid()) {
                printf("Not the winning process!");
                exit(0);
            } else {
                printf("I won!, %d", nummer);
                exit(0);
            }
            //kinderen++;
        } else {
            close(fd[1]);
            close(fd2[0]);
            int wachten = 0;
            int fout = 1;
            struct Data ontvangen;

            if ((fout = read(fd[0], (void * )( & ontvangen), sizeof(struct Data))) > 0) {
                printf("PID: %d GETAL: %d \n", ontvangen.pid, ontvangen.nummer);
                wachten++;
                if (grootste == 0 || grootste < ontvangen.nummer) {
                    printf("Compare \n");
                    grootste = ontvangen.nummer;
                    winnaar = ontvangen.pid;
                }
                printf("Compared \n");
            }
        }
    }

    int k = 0;
    for (k = 0; k < aantal; k++) {
        printf("Filling buffer...");
        write(fd2[1], (void * )( & winnaar), sizeof(int));
    }

    while (wait(NULL) > 0) {
        printf("Waiting for childs to exit");
    }
}

但是我从来没有进入缓冲区填充部分,任何可以帮助我的人?​​

由于某种原因无法使格式化工作:/。粘贴链接:http://pastebin.com/61zrC6pb

0 个答案:

没有答案