共享内存与两个过程在C? [英] Shared Memory With Two Processes In C?

查看:169
本文介绍了共享内存与两个过程在C?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要做到以下几点:

父进程创建一个子进程。然后子进程读取n个用户INT的,并将其存储在共享存储器中。随后父进程会显示出来。

Parent process creates a child process. Then the child process reads n int's from the user and store them in a shared memory. The parent process then displays them.

我得出了如下:

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#define SHMSIZE 27
int main() {
   int shmid;
   int *shm;
   int *n;

   if(fork() == 0) {
      shmid = shmget(2009, SHMSIZE, 0);
      shm = shmat(shmid, 0, 0);
      n = shm;
      int i;
      for(i=0; i<5; i++) {
         printf("Enter number<%i>: ", i);
         scanf("%d", n++);
      }
      printf ("Child wrote <%d>\n",shm);
      shmdt(shm);
   }
   else {
      wait();
      int *s;
      shmid = shmget(2009, SHMSIZE, 0666 | IPC_CREAT);
      shm = shmat(shmid, 0, 0);
      s = shm;
      wait(NULL);
      printf ("Parent reads <%d>\n",shm) ;
      shmdt(shm);
      shmctl(shmid, IPC_RMID, NULL);
   }
   return 0;
}

和输出仅仅是这一行:

Enter number<1>:

如果我进入了一个号码,比方说25,它输出这样的:

And if I entered a number, let's say 25, it outputs this:

Parent reads <r>

R:随机数-ve我每次执行code时间的变化

它从来没有通过子进程code去!我在一个错误的方式这样做呢?

It never went through the child process code ! Am I doing this in a wrong way ?

推荐答案

我的问题是如此愚蠢。我需要提供子进程写入到SHM的能力。此行中,如果块:

My problem was so stupid. I need to provide the Child process with the ability to write into the SHM. This line in the if-block :

shmid = shmget(2009, SHMSIZE, 0);

会变成这个样子:

Will become like this:

shmid = shmget(2009, SHMSIZE, 0666 | IPC_CREAT);

感谢大家,特别是@JoachimPileborg:)

Thanks to you all and especially to @JoachimPileborg :)

这篇关于共享内存与两个过程在C?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆