【问题标题】:Shared memory with forked child与分叉子共享内存
【发布时间】:2015-10-13 03:10:38
【问题描述】:

我有以下代码,它应该创建一个分叉进程来执行 Collat​​z 猜想(基于传递的值),并将整数推送到共享内存中。当子进程完成后,父进程应该打印出这些值。出于某种原因,我的代码有时有效,但有时无效。从调试语句中,我可以看到值被推入,但有时打印出值的代码似乎没有执行(只是打印了一些空白行)。我在虚拟机中使用 Debian Linux。

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/shm.h>
#include <sys/mman.h>

int main()
{
   const int SIZE = 2048;
   const char *name = "SHARON";
   int  shm_fd;
   void *ptr;
   int count = 1;

   /* Setup shared memory */
   shm_fd = shm_open(name, O_CREAT | O_RDWR, 0666);
   ftruncate(shm_fd, SIZE);
   ptr = mmap(0, SIZE, PROT_WRITE, MAP_SHARED, shm_fd, 0);

   /* Get the starting value */
   int value;
   printf("Enter a positive integer value: ");
   scanf("%d", &value);
   printf("\n");
   if (value < 0)
   {
      printf("ERROR: Integer value must be positive!");
      return 1;
   }

   /* Fork child process */
   pid_t pid;
   pid = fork();

   fork();
   if (pid < 0)
   {
      fprintf(stderr, "FORK FAILED\n");
      return 1;
   }
   else if (pid > 0) /*parent process*/
   {
      wait();  /*wait for child to send */
      while (atoi((char *)ptr) != 0)   /*0 is terminate value*/
      {
         printf("%s", (char *)ptr);
         ptr += sizeof(int);
         if (atoi((char *)ptr) != 0)
            printf(", ");
      }

      printf("\n");
      shm_unlink(name);
   }
   else if (pid == 0)   /* child process */
   {
      sprintf(ptr, "%d", value);
      ptr += sizeof(value);

      while (value != 1)
      {
         if (value % 2 == 0)
            value /= 2;
         else
            value = value * 3 + 1;

         sprintf(ptr, "%d", value);
         ptr += sizeof(value);
      }
      sprintf(ptr,"0");   //push a "terminate" value
      ptr += sizeof(value);
   }
   return 0;
}

关于我做错了什么的任何提示?

【问题讨论】:

  • 可能是因为你连续两次调用fork
  • 为什么将字符串零放入共享内存中,然后增加整数零的大小?
  • 天啊,我怎么没看到?看起来这就是问题所在!就像大卫指出的那样,我还修复了推动 0 的问题。谢谢大家!

标签: c linux fork shared-memory


【解决方案1】:

有两个 fork() 调用。这将创建两个孩子。

  pid = fork();

   //fork();

你可以试试上面的。

【讨论】:

    猜你喜欢
    • 2014-06-21
    • 1970-01-01
    • 2015-07-04
    • 2013-06-11
    • 2012-11-04
    • 2014-10-08
    • 2018-08-11
    • 2012-07-21
    • 1970-01-01
    相关资源
    最近更新 更多