pborawski

Tworzenie procesow w petli for.

Oct 8th, 2012
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.27 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <unistd.h>
  3. #include <errno.h>
  4. #include <string.h>
  5. #include <sys/types.h>
  6. #include <sys/wait.h>
  7. int main(){
  8.  
  9.     printf("Mój PID = %d\n",getpid()); //indetyfikator procesu
  10.     //errno=-1;
  11.     printf("Error in fork = %d %s\n", errno,strerror(errno));
  12.     pid_t pid;
  13.     int i, iloscpowt = 10000, nieskon = 0;
  14.     for(i = 0; i < iloscpowt; i++)
  15.         switch (pid = fork())
  16.         {
  17.                 case -1: // błąd
  18.                     printf("Błąd funkcji fork() = %d, %s\n", errno, strerror(errno));
  19.                 case 0:  // proces potomny
  20.                     printf("proces potomny, mój PID = %d\n", getpid());
  21.                     printf("proces potomny, PID rodzica = %d\n", getppid());
  22.                     printf("proces potomny, wartość wywołania fork() = %d\n", pid);
  23.                     while(1)
  24.                     {
  25.                         printf("Licze do nieskonczonosci %d\n",nieskon);
  26.                         nieskon++;
  27.                         puts("p");
  28.                         sleep(1);
  29.                     }                  
  30.                     return 0;
  31.                 default: // proces macierzysty
  32.                     printf("proces macierzysty, mój PID = %d\n", getpid());
  33.                     printf("proces macierzysty, wartość wywołania fork() = %d\n", pid);
  34.                 while(1)
  35.                 {
  36.                     puts("m");
  37.                     sleep(1);
  38.                 }
  39.                     //sleep(2);
  40.         }
  41.     for(i = 0; i < iloscpowt; i++)
  42.         if(wait(0)==-1)
  43.             printf("Błąd funkcji fork() = %d, %s\n", errno, strerror(errno));
  44.        
  45.     return 0;
  46.        
  47. }
Advertisement
Add Comment
Please, Sign In to add comment