Трубы и вкладыши - PullRequest
       13

Трубы и вкладыши

2 голосов
/ 31 октября 2011

Программа просит пользователя ввести число процессов, которые будут созданы в качестве аргумента, поэтому в основном вы должны сделать что-то вроде:

$ ./program 4

. Она сгенерирует что-то вроде этого:

This is process 1 with ID 7389 and parent id 6550
This is process 2 with ID 7390 and parent id 7389
This is process 3 with ID 7391 and parent id 7390
This is process 4 with ID 7392 and parent id 7391

нужно вставить элемент в заданную позицию, поэтому в основном

$ ./program insert 3

Он должен добавить новый процесс в строке 3 и будет выглядеть примерно так:

This is process 1 with ID 7389 and parent id 6550
This is process 2 with ID 7390 and parent id 7389
This is process 3 with ID 7399 and parent id 7389  //NEW
This is process 4 with ID 7391 and parent id 7390
This is process 5 with ID 7392 and parent id 7391

IНе знаю, как сделать вставку, я был бы признателен за любую помощь или предложения, если это возможно

Спасибо

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>


int main(int argc,  char *argv[ ]) {
   pid_t childpid;             /* indicates process should spawn another     */
   int error;                  /* return value from dup2 call                */
   int fd[2];                  /* file descriptors returned by pipe          */
   int i;                      /* number of this process (starting with 1)   */
   int nprocs;                 /* total number of processes in ring          */ 
           /* check command line for a valid number of processes to generate */
   if ( (argc != 2) || ((nprocs = atoi (argv[1])) <= 0) ) {
       fprintf (stderr, "Usage: %s nprocs ID\n", argv[0]);
       return 1; 
   }  
   if (pipe (fd) == -1) {      /* connect std input to std output via a pipe */
      perror("Failed to create starting pipe");
      return 1;
   }
   if ((dup2(fd[0], STDIN_FILENO) == -1) ||
       (dup2(fd[1], STDOUT_FILENO) == -1)) {
      perror("Failed to connect pipe");
      return 1;
   }
   if ((close(fd[0]) == -1) || (close(fd[1]) == -1)) {
      perror("Failed to close extra descriptors");
      return 1; 
   }        
   for (i = 1; i < nprocs;  i++) {         /* create the remaining processes */
      if (pipe (fd) == -1) {
         fprintf(stderr, "[%ld]:failed to create pipe %d: %s\n",
                (long)getpid(), i, strerror(errno));
         return 1; 
      } 
      if ((childpid = fork()) == -1) {
         fprintf(stderr, "[%ld]:failed to create child %d: %s\n",
                 (long)getpid(), i, strerror(errno));
         return 1; 
      } 
      if (childpid > 0)               /* for parent process, reassign stdout */
          error = dup2(fd[1], STDOUT_FILENO);
      else                              /* for child process, reassign stdin */
          error = dup2(fd[0], STDIN_FILENO);
      if (error == -1) {
         fprintf(stderr, "[%ld]:failed to dup pipes for iteration %d: %s\n",
                 (long)getpid(), i, strerror(errno));
         return 1; 
      } 
      if ((close(fd[0]) == -1) || (close(fd[1]) == -1)) {
         fprintf(stderr, "[%ld]:failed to close extra descriptors %d: %s\n",
                (long)getpid(), i, strerror(errno));
         return 1; 
      } 
      if (childpid)
         break;
   }                                               /* say hello to the world */
   fprintf(stderr, "This is process %d with ID %ld and parent id %ld\n",
           i, (long)getpid(), (long)getppid());


        close(fd[0]);          /* Close unused read end */
        close(fd[1]);          /* Reader will see EOF */
        wait(NULL);             /* Wait for child */
        exit(EXIT_SUCCESS);
   return 0; 
}

1 Ответ

2 голосов
/ 31 октября 2011

Только процесс 7389 может создать дочерний процесс с родительским.

Вам понадобится какой-то способ отправки сообщения или сигнала процессу 7389 с указанием создать новый дочерний процесс.

...