Linux 使用 Fork() 将整数传递给 child 和 parent 进程的系统调用问题

Linux System Calls problems using Fork() passing ints to child and parent processes

我正在开发一个程序,它将接受一个整数并创建两个进程,一个 parent 和一个 child。 parent 将从整数中减去 5,将其传递给 child,后者将其除以 5,然后他们将重复此过程 5 次,每次打印整数的当前值。

整数可以通过文本文件传递并且可以写入和读取,或者可以使用更简单的管道。

我一直在查找所需的系统调用,并且有一个半工作程序。然而,我已经被困了几个小时,我认为我的问题是我无法让他们等待对方完成,因为我的输出不正确。

这是我到目前为止得到的。

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

int main(void)
{    
    int x=19530;
    int w=1;
    int fd[2];
    pipe(fd);
    int pid = fork();

    int k;
    for (k=0; k<5; k++) {
        if (pid>0) {
            //int x = 19530;

            if ((close(fd[0]))==-1) {
                perror("Close:");
            }

            read(fd[0], &x, sizeof(int));
            x=x-5;
            write (fd[1], &x, sizeof(int));
            printf("X in parent %d\n", x);

            close(fd[1]);
            close(fd[0]);
        } else if (pid==0) {

            if ((close(fd[1]))==-1) {
                perror("Close:");
            }

            read(fd[0], &x, sizeof(int));
            x=x/5;
            printf("X in child %d\n", x);
            write (fd[1], &x, sizeof(int));

            close(fd[1]);
            close(fd[0]);
        }
    }
    return 0;
}

但是我的输出有问题,我得到:

X in parent 19525
X in child 3905
Close:: Bad file descriptor
X in parent 19520
Close:: Bad file descriptor
X in parent 19515
Close:: Bad file descriptor
X in parent 19510
Close:: Bad file descriptor
X in parent 19505
Close:: Bad file descriptor
X in child 781
Close:: Bad file descriptor
X in child 156
Close:: Bad file descriptor
X in child 31
Close:: Bad file descriptor
X in child 6

它似乎开始得很好,但是 child 没有正确返回然后 parent 在 child 赶上之前连续运行了太多次。我也一直在尝试修复那个错误的文件描述符,但无济于事。

如有任何帮助,我们将不胜感激。

谢谢。

#include <stdio.h>
#include <unistd.h>
#include <err.h>

#define ok(x) ({ int i_ = (x); if (i_ == -1) err(1, #x); i_; })

enum { p_, c_ }; // parent, child
enum { r_, w_ }; // read, write

int main(void)
{
        int x = 19530;
        int fd[2][2];
        int pid;

        ok(pipe(fd[0]));
        ok(pipe(fd[1]));

        ok(pid = fork());

        close(fd[p_][pid ? r_ : w_]);
        close(fd[c_][pid ? w_ : r_]);

        for (int i = 0; i < 5; i++) {
                if (pid) {
                        x -= 5;
                        printf("X in parent %d\n", x);
                        ok(write(fd[p_][w_], &x, sizeof(x)));
                        ok(read(fd[c_][r_], &x, sizeof(x)));
                }
                else {
                        ok(read(fd[p_][r_], &x, sizeof(x)));
                        x /= 5;
                        printf("X in child %d\n", x);
                        ok(write(fd[c_][w_], &x, sizeof(x)));
                }
        }
        return 0;
}

管道是单向的,所以你需要两个。我使用了一些枚举来尝试让事情更容易阅读。