首页 > 解决方案 > C 父子通讯增加打印计数器

问题描述

我正在尝试编写一个程序,以便父进程和子进程可以相互通信。父进程和子进程应该打印从 1 到 100 的值,其中每个进程打印的值每次增加 1。现在我面临的问题是,我对管道一无所知。我从在线阅读材料中收集到的是,我可以使用管道来读取和写入值。我利用它在子进程中打印一些东西,并将一些东西发回给父进程。现在,我不确定如何让父母在为自己打印后返回给孩子?我知道我的代码可能全错了,但我真的不确定我应该做什么。

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

int main(int argc, const char * argv[]) {
    int fd[2];
    if (pipe(fd)== -1){
        printf("An error occured while opening the pipe\n");
    }
    int id  = fork();
    int i = 0;
    if (id == 0){
        close(fd[0]);
        printf("In child: %d", i);
        i ++;
        write(fd[1], &i, sizeof(int));
        close(fd[1]);
    } else {
        wait(NULL);
        close(fd[1]);
        int y;
        read(fd[0],&y, sizeof(int));
        close(fd[0]);
       
    }
}

标签: cprocessoperating-systempipe

解决方案


为简单起见,检查返回值和处理错误由您决定。这只会在两者之间进行0 - 9,您将不得不扩展数学。

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

int main(int argc, char *argv[])
{
    int pipefd_1[2];
    int pipefd_2[2];   
    pid_t cpid;

    pipe(pipefd_1);
    pipe(pipefd_2);

    cpid = fork();

    if (cpid == 0) {    /* Child reads from pipe 1, writes to pipe 2*/
       char cval[] = {'0'};
       close(pipefd_1[1]);          /* Close unused write and read ends */
       close(pipefd_2[0]);
       
       while (atoi(cval) != 9) {
           read(pipefd_1[0], cval, 1);
         
           printf("Child print %d\n", atoi(cval));
           
           cval[0] += 1;
           write(pipefd_2[1], cval, 1);
       }


    } else {         
        char cval[] = {'0'};   /* Parent writes buf to pipe 1 */
        close(pipefd_1[0]);          /* Close unused read end */
        close(pipefd_2[1]);
        
        while (atoi(cval) != 9) {
             write(pipefd_1[1], cval, 1);
             read(pipefd_2[0], cval, 1);
             printf("Parent print %d\n", atoi(cval));
             cval[0] += 1;
        }
    }
}

输出

在此处输入图像描述


推荐阅读