【问题标题】:using Pipes create N child and send message to parent使用 Pipes 创建 N 个子节点并向父节点发送消息
【发布时间】:2021-01-10 15:57:35
【问题描述】:

我正在尝试创建具有相同父级的 n 个子级,并从子级 -> 父级发送随机数。 现在,我有一个问题要从孩子 -> 父母发送随机 0/1。

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

int main() 
{ 
pid_t pids[10];
int i;
int n = 10;

/* Start children. */
for (i = 0; i < n; ++i) {
     if ((pids[i] = fork()) < 0) {
     perror("fork");
         abort();
  } else if (pids[i] == 0) {
   // printf("I am a child with id %d and my parent %d\n",getpid(),getppid());
    int random = rand() % 2;
    printf("\nChild send random: %d\n",random);
    write(pids[1], &random, sizeof(random));    
    exit(0);
    }
   else{
    int ran;
    read(pids[0], &ran, sizeof(ran)); // read from child
    printf("\nParent Received: %d\n", ran);
    }
  
}

wait(NULL);

 }
 

【问题讨论】:

  • read() 的第一个参数是文件描述符,而不是 pid。
  • 您没有创建任何管道。您的数组 pids 包含 PID(进程 ID)而不是文件描述符。也许你可以在这里得到一些想法:stackoverflow.com/q/18242731/10622916

标签: c linux random pipe


【解决方案1】:

问题是:

首先,读取和写入不需要像第一个参数那样的 pid,而是文件描述符;其次,为了在两个进程之间传递某些内容,您应该使用 IPC 机制,例如管道:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>   
#include <string.h>
#include <sys/wait.h>
#include <time.h>
    
    int main()
    {
      pid_t pids[10];
      int _pipe[2];
      int i;
      int n = 10;
      int random;
    
      srand(time(NULL));
    
      /* Start children. */
      for (i = 0; i < n; ++i) {
        //printf("%d\n",i);
        pipe(_pipe);
        if ((pids[i] = fork()) < 0) {
          perror("fork");
          abort();
        } else if (pids[i] == 0) { // Child
          random = rand() % 2;
          char str[2];
          sprintf(str,"%d",random);
          //printf("\nChild send random: %d\n",random);
          close(_pipe[0]);
          write(_pipe[1], str, sizeof(str));
          printf("Pipe sended: %s\n",str);
          exit(0);
        }
        else{ // Parent
          char string[1];
          close(_pipe[1]);
          read(_pipe[0],string,sizeof(string)); // read from child
          printf("pipe received: %s\n",string);
          //printf("\nParent Received: %d\n", ran);
        }
    
      }
    
      wait(NULL);
    
    }
     

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-23
    • 2015-07-30
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    • 2014-05-01
    相关资源
    最近更新 更多