过程素数之间的共享记忆在子过程中返回零
我正在研究过程之间的过程和记忆共享的概念。因此,我采用了一个示例代码,并且正在尝试调整它,以计算一个数字是否是通过内存共享的素数。代码编译并正确返回数字是否为素数。但是我注意到,如果数字为原始,而不是打印数字总是零。我在记忆共享中出错了哪里?
非常感谢您的支持
#include <stdio.h>
#include <math.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/shm.h>
int main(){
int i, j;
int prime;
int count = 0;
int *n;
int shmid;
int pid;
printf("Enter a number:");
scanf("%d", &prime);
if(prime < 0){
printf("Not a prime number!");
}
else if(prime == 0){
printf("Not a prime number!");
}
else{
shmid = shmget(5, 2*sizeof(float), IPC_CREAT | 0600 );
n = shmat(shmid, 0, 0);
pid = fork();
if(pid > 0){
count = 0;
for(j = 2; j < prime; j++){
if(prime % j == 0){
n[0] = prime;
count++;
wait(NULL);
}
}
if(count == 0){
printf("%d Is a prime number!\n", n[0]);
shmdt(n);
}
else{
printf("%d Not a prime number!\n", n[0]);
shmdt(n);
}
}
}
}
I'm studying concepts of processes and memory sharing between processes. so I took an example code and I'm trying to adapt it to calculate if a number is prime by memory sharing. The code compiles and correctly returns whether a number is prime or not. however I noticed that in case the number is Primo, instead of printing the number is always coming to zero. where am i going wrong in memory sharing?
thank you very much for the support
#include <stdio.h>
#include <math.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/shm.h>
int main(){
int i, j;
int prime;
int count = 0;
int *n;
int shmid;
int pid;
printf("Enter a number:");
scanf("%d", &prime);
if(prime < 0){
printf("Not a prime number!");
}
else if(prime == 0){
printf("Not a prime number!");
}
else{
shmid = shmget(5, 2*sizeof(float), IPC_CREAT | 0600 );
n = shmat(shmid, 0, 0);
pid = fork();
if(pid > 0){
count = 0;
for(j = 2; j < prime; j++){
if(prime % j == 0){
n[0] = prime;
count++;
wait(NULL);
}
}
if(count == 0){
printf("%d Is a prime number!\n", n[0]);
shmdt(n);
}
else{
printf("%d Not a prime number!\n", n[0]);
shmdt(n);
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
仅在数字不是 prime的情况下写入共享内存
您仅在
count
被递增(可能反复)时,。位置
n [0] = prime
在循环外的某个地方,因此两个测试count
的分支都可以通过共享内存访问整数。或直接打印
prime
,因为共享内存和叉子在此程序中都没有实际目的。除了立即退出外,儿童过程无能为力。共享内存只是现有数据的副本。请注意,您正在为单个
int
分配2 * sizeof(float)
。不要忘记,用 shmctl ,并检查所有
shm*
功能失败的返回值。You only write to the shared memory in the event that a number is not prime
when
count
is incremented (possibly repeatedly).Place
n[0] = prime
somewhere outside the loop, so both branches that testcount
can access the integer via the shared memory.Or just print
prime
directly, seeing as both the shared memory and fork serve no practical purpose in this program. The child process does nothing except immediately exit. The shared memory is just a copy of existing data.Note, you are allocating
2 * sizeof (float)
for a singleint
.Do not forget to remove shared memory segments from the system with
shmctl
, and check the return values of allshm*
functions for failure.