叉父母孩子沟通

Emi*_*ore 10 c fork ipc

我需要一些方法让父进程分别与每个孩子进行通信.

我有一些孩子需要与其他孩子分开与父母沟通.

父母有没有办法与每个孩子建立私人沟通渠道?

例如,孩子也可以向父母发送一个struct变量吗?

我是这些事情的新手,所以任何帮助都会受到赞赏.谢谢

cmc*_*cmc 35

(我假设我们在这里谈论linux)

正如您可能发现的那样,fork()它本身只会复制调用进程,它不会处理IPC.

从fork手册:

fork()通过复制调用进程来创建一个新进程.新进程(称为子进程)与调用进程完全相同,称为父进程.

fork()后最常用的处理IPC的方法是使用管道,特别是如果你想要"与每个孩子一起使用私人通信".这是一个典型且简单易用的示例,类似于您在pipe手册中可以找到的示例(不检查返回值):

   #include <sys/wait.h>
   #include <stdio.h>
   #include <stdlib.h>
   #include <unistd.h>
   #include <string.h>

   int
   main(int argc, char * argv[])
   {
       int pipefd[2];
       pid_t cpid;
       char buf;

       pipe(pipefd); // create the pipe
       cpid = fork(); // duplicate the current process
       if (cpid == 0) // if I am the child then
       {
           close(pipefd[1]); // close the write-end of the pipe, I'm not going to use it
           while (read(pipefd[0], &buf, 1) > 0) // read while EOF
               write(1, &buf, 1);
           write(1, "\n", 1);
           close(pipefd[0]); // close the read-end of the pipe
           exit(EXIT_SUCCESS);
       }
       else // if I am the parent then
       {
           close(pipefd[0]); // close the read-end of the pipe, I'm not going to use it
           write(pipefd[1], argv[1], strlen(argv[1])); // send the content of argv[1] to the reader
           close(pipefd[1]); // close the write-end of the pipe, thus sending EOF to the reader
           wait(NULL); // wait for the child process to exit before I do the same
           exit(EXIT_SUCCESS);
       }
       return 0;
   }
Run Code Online (Sandbox Code Playgroud)

代码非常简单:

  1. 父叉()
  2. 孩子从管道读取()直到EOF
  3. 父写入()到管道然后关闭()它
  4. 数据已经分享,万岁!

从那里你可以做任何你想做的事情; 只记得检查返回值和阅读dup,pipe,fork,wait...手册,他们会派上用场.

还有许多其他方法可以在进程之间共享数据,尽管它们不符合您的"私有"要求,但它们对您很感兴趣:

甚至是一个简单的文件...(我甚至使用SIGUSR1/2 信号在进程之间发送一次二进制数据......但我不建议那么哈哈.)可能还有一些我没想到的权利现在.

祝好运.