如何使用管道将数据从子进程发送到父进程以进行进程间通信?

How can I send data from child process to parent process using pipes for inter-process communication?

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



int main(void){
    
    int a[10], b[10], i;  
    
        for (i = 0; i < 10; i++){
        a[i] = rand() % 15; 
        b[i] = rand() % 10;  
    
    }
    
    int result1=0;
    int result2=0;
        if(fork() == 0){
            for (int i = 0; i < 4; i++){
                result2 += a[i]*b[i]; 
                                       }
                
                       } else { 
            for (int i = 5; i < 10; i++){
                result1 += a[i]*b[i];   
        }
        
    }

如您所见,我是 OS 的新手。

我的问题是:子进程如何将result2发送给父进程,以便我找到result1和result2的加法?我应该使用管道进行进程间通信。

我没有上传整个问题,因为它会成为一个很长的问题。

我只回答漏掉的部分

在我声明的主体下

int fb[2];

在子进程内部(for 循环之前的 IF)

close(fb[0]); 

将子进程的结果发送给父进程

write(fb[1],&result2,sizeof(int));
close(fb[1]);

父进程内部:

int result3;
read(fb[0],&result3, sizeof(int));
close(fb[0]); 

找到点积后

计算整体非常直接:

int oAll;
oAll=  (result3+result1) / 2;       
printf("%d", oAll);