分叉和共享内存无法正确添加

时间:2013-10-05 22:27:13

标签: c linux fork shared-memory

我有以下代码,其中我通过参数输入子数。我正在使用Shared Memory,我希望每个子进程将其pid编号加到共享内存中。然后我想显示共享内存的结果编号。代码的问题是我只获得最后一个pid数而不添加以前的值。这是代码:

//gcc shmem.c -o c
//./c 2

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/ipc.h>
#include <sys/shm.h>

int main(int argc, char *argv[])
{
    int i, fdShmem, quantity, j, *sumchilds;
    pid_t pid[15];

    system("clear");

    if(argc-1 < 1)
    {
        printf("Some arguments are missing\n");
        return EXIT_FAILURE;
    }

    printf("Quantity of arguments:\n\nargc: %d\n\nValues from the arguments:\n\n",argc-1);

    for(i=0;i<argc;i++)
    {
        printf("argv[%d]: %s\n",i,argv[i]);
    }

    printf("\n\n");

    fdShmem = shmget(1234,sizeof(int),IPC_CREAT|0777);

    if(fdShmem == -1)
    {
        printf("\nError creating the shared memory\n");
        return EXIT_FAILURE;
    }

    quantity = atoi(argv[1]);

    for(i=0;i<quantity;i++)
    {
        pid[i] = fork();

        if(pid[i] == -1)
        {
            printf("\nError creating the child\n");
            return EXIT_FAILURE;
        }

        if(pid[i] == 0)
        {
            printf("child [%d]\n",getpid());

            sumchilds = (int *) shmat(fdShmem,NULL,0);

            (*sumchilds) = (*sumchilds) + getpid();
            printf("The child sum %d\n",(*sumchilds));

            shmdt(sumchilds);

            return EXIT_SUCCESS;
        }
        else
        {
            /*sumchilds = (int *) shmat(fdShmem,NULL,0);
            (*sumchilds) = 0;
            shmdt(sumchilds);*/
        }
    }

    sleep(1);

    sumchilds = (int *) shmat(fdShmem,NULL,0);
    printf("All the childs sum %d\n",(*sumchilds));
    shmdt(sumchilds);

    for(j=0;j<quantity;j++)
    {
        wait(NULL);
    }

    shmctl(fdShmem,IPC_RMID,NULL);

    return EXIT_SUCCESS;
}

这是我得到的结果:

/*
Quantity of arguments:

argc: 1

Values of the arguments:

argv[0]: ./c
argv[1]: 2


Child [3662]
The child sum 3662
Child [3661]
The child sum 7323
All the childs sum 7323 
*/

每次使用时我都要附上shmem吗?还是只在一开始? 我是否必须在子进程中添加shmget才能打开它?或者没有必要?

0 个答案:

没有答案