问题
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;
}
回答1:
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));
}
回答2:
If you're going to bother with shared memory, then it's silly to try to manipulate it by read()
and write()
calls on the underlying file (which for an anonymous mapping doesn't exist anyway). If you want to communicate via read()
and write()
then just create a pipe instead, and forget about mapping and shared memory. That is in fact an entirely viable approach.
If you really do want to use shared memory for this, then use it like memory. Convert the pointer to the shared memory region to an appropriate pointer-to-object type, use ordinary assignment to write, and use ordinary variable / memory access to read. Shared memory does introduce potential issues with conflicting access and synchronization, but even that's no big deal for the simple case you describe: just have the parent process successfully wait()
for the child (or otherwise be notified of its termination) before it attempts to read whatever the child wrote.
You do have an issue with how you are setting up your mapping, however: you map sizeof(int)
bytes, but this is probably not enough for the message you attempt to write. Overall, it should look more like this:
int main(void) {
char *message;
int status;
pid_t child;
message = mmap(NULL, BUFSIZE , PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANON, -1, 0);
if (message == MAP_FAILED) {
perror("mmap");
return 1;
}
child = fork();
if ( child == -1 ) {
perror("fork");
return 1;
} else if (child == 0) {
strcpy( message, "foo\n");
} else {
wait(&status);
printf("The child wrote:\n%s\n", message);
}
return 0;
}
来源:https://stackoverflow.com/questions/31305015/how-to-read-from-write-to-anonymous-shared-mapping