我第一次尝试使用共享内存。我创建了一个子进程,然后从父进程写入共享内存,并从Child中更改它。在程序结束之前,我从父进程打印共享内存,共享内存没有改变,下面是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <semaphore.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <signal.h>
sem_t *semaphore;
int main(){
int i = 0, status;
pid_t pid=fork(), w;
int id;
if ((id = shmget(IPC_PRIVATE, sizeof(int), IPC_CREAT | 0666)) == -1){
perror("shmget");
exit(1);
}
int *sh;
if ((sh =(int *) shmat(id, NULL, 0)) == NULL){
perror("shmat");
exit(1);
}
*sh = 10;
if ((semaphore = sem_open("/semaphore", O_CREAT, 0666, 0)) == SEM_FAILED){
perror("semaphore");
exit(1);
}
if (pid==0) {
while(1){
sleep(1);
*sh = 50;
printf("child %d, %d\n", i, *sh);
i++;
if(i == 5){
sem_post(semaphore);
exit(0);
}
}
} else if (pid==-1) {
perror("process error\n");
} else {
printf("Parent, %d\n", *sh);
sem_wait(semaphore);
printf("child end => parent end\n");
printf("Parent, %d\n", *sh);
}
shmctl(id, IPC_RMID, NULL);
sem_close(semaphore);
sem_unlink("/semaphore");
return 0;
}如果我有点理解共享内存,那么我可以从任何地方更改它,如果在我的例子中有一个指针,那就是"sh“。
程序的输出是:
Parent, 10
child 0, 50
child 1, 50
child 2, 50
child 3, 50
child 4, 50
child end => parent end
Parent, 10为什么共享内存中的数字在父母和儿童中是不同的?
发布于 2015-04-11 15:33:42
在使用键fork()创建共享内存之前,您可以先使用IPC_PRIVATE创建共享内存,这样两个进程都会创建自己的共享内存,而不会实际共享它。
如果您将=fork()从
pid_t pid=fork(), w;和插入
pid = fork();在shmget调用之后的某个地方,它按照您预期的方式工作,因为子进程将继承父进程的共享内存标识符,而不会创建不同的标识符。
https://stackoverflow.com/questions/29579521
复制相似问题