0

难以使两个进程通过管道通信并交替减去一个数字。

输出应该是这样的: process1: 9 process2: 8 process1: 7 ...

到目前为止我所做的:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main() {
    int p2c[2];
    int c2p[2];
    int n = 9;

    pipe(p2c);
    pipe(c2p);

    write(p2c[1], &n, sizeof(int));

    if(fork() == 0) {
        read(p2c[0], &n, sizeof(int));
        printf("Got from parent: %d", n);
    n--;
    write(c2p[1], &n, sizeof(int));
    close(p2c[0]);
    close(p2c[1]);
    close(c2p[0]);
    close(c2p[1]);
    exit(0);
}
else{
    read(c2p[0], &n, sizeof(int));
    printf("Got from child: %d", n);
    n--;
    write(p2c[1], &n; sizeof(int));
    close(p2c[0]);
    close(p2c[1]);
    close(c2p[0]);
    close(c2p[1]);

}
return 0;
}

输出:从父母获得:9 从孩子获得:8 让这两个进程减去数字直到 0 的正确方法是什么?

4

1 回答 1

1

有意义的是,您只会得到“ Got from parent:9 Got from child:8 ”因此,您需要,您需要一个whilefor循环来让进程和进程都获得您所期望的,并且这些循环的停止条件是(n < 0)在递减n或管道的端关闭后:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main() {
    int p2c[2];
    int c2p[2];
    int n = 9;

    pipe(p2c);
    pipe(c2p);

    // this is important to prevent deadlock situation, at least one of both processes
    // must start a write operation before while loop, unless the read will block and 
    // and each process still waiting the other to write something on the pipe
    write(p2c[1], &n, sizeof(int));

    if(fork() == 0) {
        int readStatus;
        while(1){
            readStatus=read(p2c[0], &n, sizeof(int));
            // when read returns 0, this means the write end of pipe was closed, so we have to break the loop
            // because no more data to recieve
            if(readStatus == 0) break;
            printf("Got from parent: %d\n", n);
            n--;
            // we check if n less than 0, if yes we are finished
            if(n < 0) break;
            write(c2p[1], &n, sizeof(int));
        }
        close(p2c[0]);
        close(p2c[1]);
        close(c2p[0]);
        close(c2p[1]);
        exit(0);
    }
    else{
        int readStatus;
        while(1){
            readStatus= read(c2p[0], &n, sizeof(int));
            if(readStatus == 0) break;
            printf("Got from child: %d\n", n);
            n--;
            if(n < 0) break;
            write(p2c[1], &n, sizeof(int));   
        } 

        close(p2c[0]);
        close(p2c[1]);
        close(c2p[0]);
        close(c2p[1]);

    }
    return 0;
}
于 2014-05-17T12:56:35.543 回答