如何从/write读取到匿名共享映射? [英] How to read from /write to anonymous shared mapping?
本文介绍了如何从/write读取到匿名共享映射?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
尝试使用子进程将消息写入匿名共享内存,请终止该消息.然后让家长阅读该消息.我已经看到了映射输入&的示例.使用通过read
& write
通话.但是不知道如何正确地解决这个问题.
Attempting to write a message to anonymous shared memory with a child process, terminate it. Then have the message read by the parent. I have seen examples for mapping input & output files using file descriptors obtained through read
& write
calls. But do not know how to approach this correctly.
int main(void) {
char *shared;
int status;
pid_t child;
shared = mmap(0, sizeof(int) , PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, -1, 0);
if (shared == MAP_FAILED) {
perror("mmap");
return 1;
}
child = fork();
if ( child == -1 ) {
perror("fork");
return 1;
} else if (child == 0) {
sprintf(shared, "foo");
} else {
printf("%s", shared);
wait(&status);
}
if (munmap (shared, sizeof(int)) == -1) {
perror("munmap");
return 1;
}
return 0;
}
推荐答案
如果您的唯一目标是在子进程和父进程之间进行读/写,则使用管道是一种更简单的方法.看起来像这样:
If your only goal is to read / write between a child process and a parent process, using pipes is a much easier method of doing so. It would look something like this:
int fd[2];
pipe(fd);
if((child= fork()) == -1)
{
perror("fork");
exit(1);
}
if(child == 0)
{
// close read side
close(fd[0]);
// write to pipe
write(fd[1], msg, (strlen(msg));
}
else
{
//close write side
close(fd[1]);
//read what the child wrote.
nbytes = read(fd[0], buff, sizeof(buff));
}
这篇关于如何从/write读取到匿名共享映射?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文