c - 将结构数组放入unix中的共享内存中,以便客户端程序可以访问它

标签 c arrays unix struct shared-memory

所以我目前正在尝试使用共享内存和 fork() 函数在 unix 中进行编码,我有一个包含 10 个结构的数组,我想将该数组放入共享内存中,以便客户端可以访问它程序。我希望有人能指出我如何做到这一点的正确方向。

我目前拥有的代码是:

//  Compiler Directives


//  Standard Library Inclusions
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>
#include <time.h>
//Other Inclusions

struct strProcess 
{
  int nPriority;
  int nPid;
};
//  Function Prototypes (if not included within a header file)
int frand (int nInput);
int finval (int nInput);
void fsortasc(struct strProcess pArray[],int nInput);
//  Main
int main(void)
{
// Variable Declarations
int     nShmid,i,arraySize,nRpriority,j, nInput;
key_t   nKey;
char    *ptrshm, *ptrs;
int     nSize;
pid_t   pid; 
struct  strProcess pArray[10];
struct  strProcess *Array;

Array = pArray;
// Code start

nKey = 5678;
FILE *f = fopen("logfile.txt", "w");

if (f == NULL)
{
      printf("Error opening file!\n");
      exit(1);
}

printf("please enter the amount of processes to create for this cycle between 1 and 10 \n");
scanf("%d",&nInput);
if (nInput <= 0 || nInput > 10)
{
  nInput = finval(nInput);
}
printf("%d", nInput);

nSize = sizeof(pArray) * 10;
 //create segment
if ((nShmid = shmget(nKey,nSize, IPC_CREAT | 0666)) <0)
{
      perror("shmget");
      exit(1);
}
printf("segment created \n\n");
fprintf(f, "shared memory segment created");

Array *pArray = shmat(shmid,NULL, 0);
if (Array* pArray (-1)) 
{
      perror("shmat");
      exit(1);
}
printf("segment attached \n\n");
fprintf(f, "shared memory segment attached");

for(i = 0 ; i < nInput; i++)
{
    if ((pid = fork()) < 0)
    {
      perror("fork");
      exit(1);
    }
    if (pid == 0)
    {
      Array[i].nPid = getpid();
      nRpriority = frand(nInput);
      Array[i].nPriority = nRpriority;
      printf("print job created with Pid %d and priority number %d", 
      getpid(), nRpriority);
      fprintf(f, "print job created with Pid %d and priority number %d", 
      getpid(), nRpriority);
    }
}

fprintf(f, " %d processes have been created", nInput);
fsortasc(pArray, nInput);   /*sort array into ascending order by nRpriority values*/

// Function Definitions - in alphabetical order
int finval (int nInput)
{
while(nInput <= 0 || nInput > 10)                               
{
    printf("please enter a number between 1 and 10 \n");
    scanf("%d", &nInput);                                       
} 
return nInput;                                                
}

int frand (int nInput)
{   
int nRand;
nRand = (rand() % nInput)+1;                  /*set nRand == a random number 
                                               inbetween nInput and 1*/
return nRand;                                 /*return the random number*/
}

void fsortasc(struct strProcess pArray[],int nInput)  
{
struct strProcess temp;     /*temporary storage for elements being swapped*/
int i, j;

for (i = 0; i < nInput - 1; i++)                                 
{
    for (j = 0; j < (nInput - 1-i); j++)
    {
        if (pArray[j].nPriority > pArray[j + 1].nPriority)                      /*if the current element is greater than the next element*/
        {
            temp = pArray[j];                                                   
            pArray[j] = pArray[j + 1];                                          
            pArray[j + 1] = temp;                                               
        }                                                                       
    }
}

最佳答案

我有一个包含 10 个结构体的数组,我想将该数组放入共享内存中?很简单,首先创建 array 10 struct variable然后创建shared memory使用shmget所需数量 size然后attachshared memorypointer最后copy将 10 个结构体数组放入附加有 shmat 的指针中。我添加了以下简单的代码来了解您的需求。

typedef struct company {
        int emp_id;
}cmp;
int main(int argc,char *argv[]) {
        cmp cmp_info[10];
        int shm_id, sze = sizeof(cmp_info) ,i;
        /* I have an array of 10 structs -- with some data like emp_id*/
        for(i=0 ;i<10 ;i++) {
        printf("\n enter emp % Id \n",i);
        scanf("%d",&cmp_info[i].emp_id);
        }
        /* create the shared memory of 'sze' size. */
        shm_id = shmget(10,sze, IPC_CREAT | 0664);
        perror("shmget");
        /* attach the shared memory with shm_id */
        cmp *shm_ptr = shmat(shm_id, NULL, 0);
        perror("shmat");
        /* I have an array of 10 structs and I would like to put that array into shared memory  */
        shm_ptr = cmp_info;//now shared memory contains array of 10 struct data 

        /** print using shm_ptr to verify **/
        for(i=0;i<10;i++) {
        printf("Employee[%d] Id is : [%d]\n",i,shm_ptr[i].emp_id);
        }
        /* once above things are done clients program can read from shared memory */
        /** finaly de-atach the shared memory */
        shmdt(shm_ptr);
}

下面的快照是您的代码,说明在注释中。

struct strProcess {
        int nPriority;
        int nPid;
};
int main(int argc,char *argv[]) {
        // Variable Declarations
        int     nShmid,i,arraySize,nRpriority,j, nInput;
        key_t   nKey;
        char    *ptrshm, *ptrs;
        int     nSize;
        struct  strProcess pArray[10];//array of 10 structure
        struct  strProcess *Array;
        //Array = pArray;
        nKey = 5678;
        FILE *f = fopen("logfile.txt", "w");
        if(f == NULL) {
                printf("Error opening file!\n");
                exit(1);
        }
        nSize = sizeof(pArray);
        //create segment
        if((nShmid = shmget(nKey,nSize, IPC_CREAT | 0666)) < 0) {
                perror("shmget");
                exit(1);
        }
        else {
                perror("shmget");
                fprintf(f, "\n shared memory segment created\n");
        }
        Array  = shmat(nShmid, NULL, 0);
        perror("shmat");
        /** loop to create exaCtly 10 process */
        nInput = 10; /** call finval function **/
        for(i = 0 ; i < nInput; i++) {
                if(fork() == 0) {
                        srand(getpid());
                        Array[i].nPid = getpid();
                        nRpriority = rand()%10 + 1;//putting random no b/w 1 to 10..u can call your function also
                        Array[i].nPriority = nRpriority;
                        fprintf(f, "\nprint job created with Pid [%d] and priority number [%d]\n",
                                        Array[i].nPid, Array[i].nPriority);
                        break;//must to avoid repeating
                }
                else {
                        ;//parent does nothing
                }
        }
        shmdt(Array);
        //fprintf(f,"\n total [%d] processes have been created\n",nInput);
        /* call fsortasc(pArray, nInput); */
        fclose(f);
}

希望对您有帮助。

关于c - 将结构数组放入unix中的共享内存中,以便客户端程序可以访问它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48078841/

相关文章:

c - 为什么 C 向我的 char 数组添加奇怪的字符?

c - int *p = &a 和 q = &a 有什么区别

python - 将多维数组从 perl 脚本传递到 python 脚本

c++ - MS VC++ 将字节数组转换为 BSTR?

c++ - CS高级项目思路涉及Unix系统编程

java - 如何使用java实现expect "interact"命令

linux - 将 sed 应用于 crontab 行?

c - 数组元素在函数外是 "lost"

在 C 中创建和初始化具有可变长度宏的结构

你能把一个没有方括号或下标的数组加到一个整数上吗?结果是什么?