使用shmat后无法在标准输出上打印

时间:2015-02-26 22:16:27

标签: c unix output shared-memory fgets

因此在此代码中puts无法显示输出。

如果我删除了fgets行,则会打印lola,但如果我尝试在shm上进行读写,则不会发生任何事情。我该如何解决这个问题?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/types.h>

#define SHMSZ 4096

int
main()
{
  pid_t pid1, pid2, pid3;
  pid1 = fork();
  if (pid1 == 0)
    {
      /* child1 */
      int shmid;
      key_t key;
      char * shm;
      key = 5678;
      if ((shmid = shmget(key, SHMSZ, IPC_CREAT | 0666)) < 0)
        {
          perror("shmget");
          exit(1);
        }
      if ((shm = shmat(shmid, NULL, 0)) == (char *) -1)
        {
          perror("shmat");
          exit(1);
        }
      printf("alright");
      if (fgets(shm,60,stdin))
        {
          /* This doesn't print. */
          puts(shm);
        }
      else
        {
          printf("hurara");
        }
      printf("lola");
    }
  else
    {
      pid2 = fork();
      if(pid2 == 0)
        {
          /* child2 */
        }
      else
        {
          pid3 = fork();
          if (pid3 == 0)
            {
              /* child3 */
            }
          else
            {
              /* parent */
              wait(0);
              wait(0);
              wait(0);
            }   
        }
    }
  return 0;
}

1 个答案:

答案 0 :(得分:0)

您的#include存在问题。你编译时有警告吗?如果我使用这些(注释问题),程序将编译干净并按照我的假设行事。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ipc.h>
/* #include <sys/sem.h> */    /* this one is not needed... */
#include <sys/shm.h>          /* ...but this one is */
#include <sys/types.h>
#include <sys/wait.h>         /* was missing, needed for wait() */
#include <unistd.h>           /* was missing, needed for fork() */