【问题标题】:cross memory attach. Not able to send the remote address using pipes跨内存附加。无法使用管道发送远程地址
【发布时间】:2013-06-26 16:35:22
【问题描述】:

我问过关于跨内存附加的问题 (cross memory attach. How do I get the remote address from a child process to a parent process)

我正在使用管道将地址从子进程传输到父进程。 代码:

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

}

父级从“readbuffer”指针中的子级接收字符串的地址。但是我看不到孩子发送的“字符串”的地址。如果我正确使用管道,请告诉我。

【问题讨论】:

  • 看不到地址是什么意思?如果打印出来,是数字吗?

标签: c unix ipc


【解决方案1】:

指针和值之间有很多混淆。 write(readbuffer) 发送 readbuffer 指向的内存,但 sizeof(readbuffer) 是指针本身的大小。在父子句中,您尝试读取 readbuffer 指向的缓冲区,由于 readbuffer 未初始化,该缓冲区应该会崩溃。

您可能想要write(fd[1], &amp;readbuffer, sizeof(readbuffer)) 和read(),然后确保将readbuffer 作为指针打印,正如@alk 所述。如果您这样做,请将变量 readbuffer 重命名为更能反映其使用情况的名称。

【讨论】:

  • 我在阅读时没有使用 & 符号。这很有帮助。非常感谢。
【解决方案2】:

在父级中应该是:

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

作为指针值(地址)应打印,而不是它指向的“字符串”。


此外,代码不能确保接收到 sizeof(readbuffer) 字节,甚至不能确保对 read() 的调用没有失败。


更新:

Peter 在他的回答中也提到,要读取/写入 readbuffer 的值,必须将其地址传递给 write()/read():

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

...

nbytes = read(fd[0], &readbuffer, sizeof(readbuffer));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-08
    • 1970-01-01
    • 2018-12-23
    • 2014-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多