【发布时间】:2019-05-02 17:06:52
【问题描述】:
我试图让两个子进程将两个随机整数写入共享内存,然后让父进程读取它们。 我似乎无法验证写入,因为每当我尝试访问父进程中的数组元素时都会遇到分段错误。
在写入后立即尝试从子进程中的内存读取什么都不做。
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <time.h>
#include <stdlib.h>
#include <sys/ipc.h>
#include <sys/shm.h>
int main(){
srand(time(NULL));
int pid2;
key_t key = 12345;
int shmid = shmget(key, 2 * sizeof(int), IPC_CREAT|IPC_EXCL|0666);
int *array = (int *)shmat(shmid, 0, 0);
int pid1 = fork();
//write first array element
if (pid1 == 0){
int n1 = rand() % 10;
printf("I'm process number 1, my pid is %d and my number is %d\n", getpid(), n1);
array[0] = n1;
return 1;
}
if (pid1 > 0){
int pid2 = fork();
if (pid2 == 0){
//write second array element
int n2 = rand() % 10;
printf("I'm process number 2, my pid is %d and my number is %d\n", getpid(), n2);
array[1] = n2;
return 1;
}
}
waitpid(pid1, NULL, 0);
waitpid(pid2, NULL, 0);
//segmentation fault happens here
printf("%d\n", array[0]);
return 0;
}
【问题讨论】:
-
关于:
int pid2 = fork();这使得pid2成为一个局部变量,与pid2的初始声明和后面的引用完全无关:waitpid(pid2, NULL, 0);这是一个需要更正的严重错误.建议:将:int pid2 = fork();替换为pid2 = fork();,以便它使用“函数范围”变量实例,而不是仅在当前代码块中可见的变量 -
在父进程退出之前,它应该调用
shmdt()来分离通过shmat()附加的共享内存 -
函数:
fork()有 3 个不同的返回值:代码无法检查返回值 fork() 总是成功的。这是一个非常冒险的假设,代码不应该做出 -
@user3629249 错过了,谢谢!
标签: c interprocess