使用管道写入和读取 Int 数组

Dou*_*son 1 c arrays fork pipe

我正在尝试使用管道制作一个简单的程序。程序必须请求父级中的整数数组,并将其发送给子级,子级必须对数组进行排序并将其发送回父级。问题是,在通过管道发送后,我不确定如何读取孩子中的数组值。

按照我的代码:

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

int main() {

int fd[2];
pid_t pid;

/* Verifica se ocorreu erro (-1) ao criar o PIPE */
if(pipe(fd) == -1){
    perror("pipe");
    exit(1);
}

/* Verifica se o fork foi realizado com sucesso > 0 */
if((pid = fork()) < 0){
    perror("fork");
    exit(1);
}

if(pid > 0){

    printf("-----------------------------------------------\n");
    printf("                PROCESSO PAI                   \n");
    printf("-----------------------------------------------\n");

    /* Como vamos ESCREVER do lado do PAI, fechamos a LEITURA */
    close(fd[0]);

    int numeros[5];

    for (int i = 0; i < 5; i++){
        printf("\nDigite o numero [%d]: ", i);
        scanf("%d", &numeros[i]);
    }

    /* Escrevendo o array no PIPE */
    write(fd[1], numeros, sizeof(numeros) + 1);
    printf("\nEnviando numeros para meu Filho...\n");
    exit(0);

}else{

    int numeros_recebidos[5];

    /* Como vamos LER do lado do FILHO, fechamos a ESCRITA*/
    close(fd[1]);

    /* Lendo a mensagem que foi enviada pelo FILHO */
    read(fd[0], numeros_recebidos, sizeof(numeros_recebidos));
    printf("\n-----------------------------------------------\n");
    printf("                PROCESSO FILHO                 \n");
    printf("-----------------------------------------------\n");

    printf("\nNumeros Recebidos, Ordenando...\n");


    for(int i = 0; i<5; i++){
        printf("%d \n", &numeros_recebidos[i]);
    }
}

return 0;
}
Run Code Online (Sandbox Code Playgroud)

Ach*_*hal 5

你的程序运行良好,除了一些错误

 for(int i = 0; i<5; i++){
        printf("%d \n", &numeros_recebidos[i]); // why &, remove it bcz you are printing data not scanning.
Run Code Online (Sandbox Code Playgroud)

孩子和父母如何通过管道通信

pipe() 有一些重要的事情:

1)pipe()系统调用会创建两端调用fd[0]fd1[1]。一个是为reading目的而保留的,另一个是为目的而保留的writing

2)pipe是一个uni-directional IPCie 一次只能从/向管道的一端读取或写入,两者不能同时进行。

3)只有相关进程(如子进程和父进程)才能通过pipe().

父进程:父进程正在将整数数组写入fd[1]. 一旦完成,现在数据在pipe(). 接下来是从这里读取数据的子作业,所以让我们跳到子进程。

                            pipe(uni-directional)
                       |---------------------------| 
parent is writing----->|                           |<---------
                       |---------------------------| 
                     fd[1]                        fd[0]

        write(fd[1], numeros, sizeof(numeros) + 1);
Run Code Online (Sandbox Code Playgroud)

child process :父已将 int 数组放入 fd[1] 现在子必须从 fd[0] 读取并打印它。

          pipe(uni-directional)
      |---------------------------| 
----->|                           |<-----child process is reading data & storing in numeros_recebidos
      |---------------------------| 
     fd[1]                       fd[0]

  read(fd[0], numeros_recebidos, sizeof(numeros_recebidos));
Run Code Online (Sandbox Code Playgroud)

我希望它有助于理解 pipe() 的工作原理。