c - parent 和 1 个 child 之间的 IPC。

标签 c ipc

我正在练习父进程和 1 个子进程之间的进程通信。我想要做的是, child 发送的每条消息都由 parent 读取(某种阻塞发送, parent 必须先阅读该消息,然后 child 才能继续发送另一条消息)。我不能使用管道。我读过 Silberschatz 的关于阻止发送的书,但我还没有找到一个很好的例子(也许还有邮箱)。你能帮忙的话,我会很高兴! 这是一段代码:

int main(int argc, char** argv) {
printf("This process: ");
printf("%d\n",getpid());
printf("Parent: ");
printf("%d\n",getppid());
pid_t f;
int input;
f = fork();
if (f == 0) {
    for(int i=0;i<5;i++){
        printf("Input a number: ");
        scanf("%d",&input);
        send(getppid(),input);
    }
    printf("\n");
    exit(0);
} else { 
recv(f,input);
printf("%d",input);
}
wait();
exit(0);

}

最佳答案

这是一个可怕的黑客,但有效:/ 您应该使用信号量或某种向共享内存发送信号的方式。 为 ftok 创建文件 (createthisfile.txt)。 这是对共享内存块进行密集轮询,并使用“代码”(int = 99)来指示父级子级 for 循环已完成。请注意,99 不能用作数字,否则家长将提前退出。最后一点,如果你正在学习这个,那么你应该自己解决你的问题,获得技巧和提示,但不要让别人为你做工作:/否则你将主修 stackoverflow,而不是计算机科学:) 我做到了这是一个快速练习,但很遗憾发布它:/

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

int main(int argc, char** argv) {
   key_t k;
   pid_t f;
   int shmid;
   int input;

   printf("This process: ");
   printf("%d\n",getpid());
   printf("Parent: ");
   printf("%d\n",getppid());

   k = ftok ("createthisfile.txt", 'R');
   shmid = shmget(k, sizeof(int), IPC_CREAT|SHM_R|SHM_W);
   char *addr = shmat(shmid,0,0);

   f = fork();

   if (f == -1) {
      exit(1);
   }

   if (f == 0) {
      for(int i=0;i<5;i++){
         printf("Input a number: ");
         scanf("%d",&input);
         memcpy(addr, &input, sizeof(int));
      }
      input = 99;
      memcpy(addr, &input, sizeof(int));
      printf("\n");
      exit(0);
   } else { 
      while (1) {
         memcpy(&input, addr, sizeof(int));
         if (input != 0) { 
            if (input == 99) {
               exit (0);
            }
            printf("[Parent reads: %d]\n",input);
            input = 0;
            memcpy(addr, &input, sizeof(int));
         }
      }
   }

   exit(0);
}

关于c - parent 和 1 个 child 之间的 IPC。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43524438/

相关文章:

c - C 中的 union 来处理将多种类型的指针传递给函数

c - 打印 C 中指针的值

c - 在 linux (ubuntu) 上用 C 语言延迟向我自己的进程发送信号

perl - 如何从 Perl 脚本中运行 Perl 脚本?

c - 我这样做对吗?将结构中的指针映射到结构外部以供 IPC 共享内存使用

python - 将popen输出重定向到python中的文件

c - 用于删除 C 代码中所有循环的工具

C结构问题

c++ - 有没有在 C/C++ 代码中使用 mbind 的例子?

c - SetSecurityInfo 返回拒绝访问