Shared Memory With Two Processes In C?

后端 未结 4 1511
鱼传尺愫
鱼传尺愫 2021-01-03 07:42

I want to do the following:

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

4条回答
  •  无人及你
    2021-01-03 08:09

    Ok, better collect in an answer instead...

    There are several problems with you program. If you enable warnings when building (I use -Wall -Wextra) a lot of them will be quite evident.

    The first two problems I already mentioned in my comments, but I explain them here:

    1. The first is the call to wait(). There is no wait function in C or POSIX that takes no argument.
    2. The second problem is the scanf call, you are calling it with *++, where *n takes the value of the memory pointed to by n which most likely can result in a crash. Remove the asterisk.
    3. The third problem is that you treat the shared memory as both an array of integers (with n) and as a string. You cant really do both, pick one or the other.
    4. You create the shared memory in the parent process, but wait for the child process to finish before you create the memory.
    5. There is a race condition between the parent and child process, since the share memory might be created after the child tries to access it.

    Edit I came up with this instead, which seems to work for me. I added comments on the things I changed.

    #include 
    #include 
    #include 
    #include 
    #include   /* Needed for the wait function */
    #include     /* needed for the fork function */
    #include     /* needed for the strcat function */
    #define SHMSIZE 27
    int main() {
       int shmid;
       char *shm;
    
       if(fork() == 0) {
          shmid = shmget(2009, SHMSIZE, 0);
          shm = shmat(shmid, 0, 0);
          char *s = (char *) shm;
          *s = '\0';  /* Set first location to string terminator, for later append */
          int i;
          for(i=0; i<5; i++) {
             int n;  /* Variable to get the number into */
             printf("Enter number<%i>: ", i);
             scanf("%d", &n);
             sprintf(s, "%s%d", s, n);  /* Append number to string */
          }
          strcat(s, "\n");  /* Append newline */
          printf ("Child wrote <%s>\n",shm);
          shmdt(shm);
       }
       else {
          /* Variable s removed, it wasn't used */
          /* Removed first call to wait as it held up parent process */
          shmid = shmget(2009, SHMSIZE, 0666 | IPC_CREAT);
          shm = shmat(shmid, 0, 0);
          wait(NULL);
          printf ("Parent reads <%s>\n",shm) ;
          shmdt(shm);
          shmctl(shmid, IPC_RMID, NULL);
       }
       return 0;
    }
    

    Do note that point 5 in the list above have not been resolved.

提交回复
热议问题