cross memory attach. Not able to send the remote address using pipes

依然范特西╮ 提交于 2019-12-08 13:50:41

问题


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.


回答1:


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));



回答2:


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.



来源:https://stackoverflow.com/questions/17325712/cross-memory-attach-not-able-to-send-the-remote-address-using-pipes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!