0

I had asked my question on cross memory attach (cross memory attach. How do I get the remote address from a child process to a parent process)

I am using pipes to transfer the address from child process to parent process. Code:

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

int main()
{
int i, nbytes;  //nbytes to keep a count of the no. of bytes received
int fd[2];  //file descriptor
int pid1, ppid;
char temp;  
char string[] = "hello world\n";
char *readbuffer = NULL;

int address;

ppid = getpid();
printf("I am the parent process pid : %d \n", ppid);

pipe(fd);
pid1 = fork(); //child A

if(pid1 == -1){
    perror("fork");
    return 1 ;
}

if(pid1 == 0){ //body of the child process
    readbuffer = string;
    printf("child process A with pid : %d\n",getpid());
    printf("Address of the string : %p\n", readbuffer);
    //snprintf(string, 80,"%p\n",address);
    close(fd[0]);
    write(fd[1], readbuffer, sizeof(readbuffer));
} else {
    printf("I am the parent : %d\n", getpid());
    close(fd[1]);
    nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
    printf("The address of the rcvd buffer : %s\n", readbuffer);
}

return 0;

}

The parent receives the address of the string from child in the "readbuffer" pointer. But I am not able to see the address of the "string" sent from the child. Please let me know if I am using pipes correctly.

Community
  • 1
  • 1
patro
  • 111
  • 2
  • 10

2 Answers2

1

Lots of confusion between pointers and values. write(readbuffer) sends the memory pointed to by readbuffer, but sizeof(readbuffer) is the size of the pointer itself. In the parent clause, you are trying to read into the buffer pointed to by readbuffer, which should crash because readbuffer is not initialized.

You probably want to write(fd[1], &readbuffer, sizeof(readbuffer)) and likewise the read(), and then be sure you're printing readbuffer as a pointer, as mentioned by @alk. If you do it this way, rename the variable readbuffer to something that better reflects its usage.

Peter
  • 14,559
  • 35
  • 55
0

In the parent it should be:

printf("The address of the rcvd buffer : %p\n", (void *) readbuffer);

as a pointer value (an address) shall be printed not the "string" it's pointing to.


Also the code does not make sure that sizeof(readbuffer) bytes were received, not even that the call to read() did not fail.


Update:

As also mentioned by Peter in his answer, to read/write the value of readbuffer it is necessary to pass its address to write()/read():

write(fd[1], &readbuffer, sizeof(readbuffer));

...

nbytes = read(fd[0], &readbuffer, sizeof(readbuffer));
alk
  • 69,737
  • 10
  • 105
  • 255