It is not a hard doubt, but I'm not sure.
My questions:
The code is as follows:
#include <sys/types.h>
#include <stdbool.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#define DIM 100000
int main(void){
printf("\n Buffer del sistema = %d\n ",BUFSIZ);
int bytes_sent = 0, bytes_read = 0, i = 0, *FD=NULL;
FD = (int*)calloc(2,sizeof(int));
int *buffer = (int*)calloc(1,sizeof(int));
int pid = 0;
if(!pipe(FD)){
pid = fork();
if (pid < 0){
perror("Error al crear bifurcación");
exit(pid);
}
if (pid == 0){
for(i=0;i<=27;i++){
bytes_read = read(*FD,buffer,8);
printf("\nEl proceso hijo ha leído %d bytes.\nEl contenido es: %p\n", bytes_read,*(buffer));
}
exit(0);
}
else{
int a = 10, *z = &a;
int **pp = &z;
printf("\nApuntador: %p\n", z);
for(i=DIM;i<DIM+30;i++){
bytes_sent = write(*(FD+1),pp,sizeof(int*));
printf("\nEl proceso padre ha enviado %d bytes\n",bytes_sent);
usleep(DIM);
}
}
}
return 0;
}
And the output at execution is this:
Buffer del sistema = 8192
Apuntador: 0x7ffedc1370ec
El proceso padre ha enviado 8 bytes
El proceso hijo ha leído 8 bytes.
El contenido es: 0xdc1370ec
... some repeated output here ...
El proceso hijo ha leído 8 bytes.
El contenido es: 0xdc1370ec
El proceso padre ha enviado 8 bytes
El proceso padre ha enviado 8 bytes
------------------
(program exited with code: 0)
Press return to continue
Thanks in advance!
The problem is that buffer
is declared as a pointer to int
, but it should be a pointer to pointer to int
. Thus the value that the child process is printing, *(buffer)
, is not passed as a pointer, but an int
which apparently is 4 bytes on your system while a pointer is 8 bytes.
To fix this, change the line
int *buffer = (int*)calloc(1,sizeof(int));
into
int **buffer = (int**)calloc(1,sizeof(int *));