根据你提供的代码,问题可能出在子进程中读取共享内存时没有等待父进程写入完成。由于共享内存是一种进程间通信机制,所以需要确保写入和读取操作按照正确的顺序进行。
在你的代码中,子进程需要等待父进程写入完毕后才能读取。可以尝试在子进程中加入延迟(例如使用sleep()
函数)来确保父进程有足够的时间将数据写入共享内存。
修改后的代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <sys/mman.h>
int main() {
int fd, i;
char *p;
pid_t pid;
fd = open("brotest", O_RDWR|O_CREAT|O_TRUNC, 0644);
if (fd == -1) {
perror("open error");
exit(1);
}
ftruncate(fd, 4096);
p = mmap(NULL, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (p == MAP_FAILED) {
perror("mmap error");
exit(1);
}
close(fd);
for (i = 0; i < 2; i++) {
pid = fork();
if (pid == 0) {
break;
}
}
if (i == 2) {
sleep(1); // 等待父子进程完成通信
wait(NULL);
wait(NULL);
int ret = munmap(p, 4096);
if (ret == -1) {
perror("munmap error");
exit(1);
}
printf("回收子进程成功\n");
}
if (i == 0) { // 写入数据
strcpy(p, "hi bro!\n");
}
if (i == 1) { // 读取数据
printf("收到:%s\n", p);
}
return 0;
}
在这个修改后的代码中,我们使用 sleep(1)
函数来确保父进程有足够的时间将数据写入共享内存,然后子进程再进行读取。这样可以避免子进程在父进程完成写入之前尝试读取共享内存导致获取不到数据的问题。
内容由零声教学AI助手提供,问题来源于学员提问