Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jul 29th, 2012  |  syntax: None  |  size: 1.15 KB  |  hits: 13  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. fork() in for() loop
  2. #include <stdio.h>
  3. #include <unistd.h>
  4. #include <stdlib.h>
  5. #include <sys/types.h>
  6. #include <sys/wait.h>
  7.  
  8. int main(int argc, char *argv[]){
  9.     int limit = argc/2;
  10.     if(argc%2 == 0){
  11.  
  12.             perror("the number of arguments given must pe even!");
  13.             exit(1);
  14.     }
  15.  
  16.     int i;
  17.     for(i=0; i<=limit; i++){
  18.         if(fork()==-1){
  19.             perror("childes couldn't be createdn");
  20.             exit(1);
  21.         }
  22.         if(fork()==0){
  23.             printf("fork: %d n",i);
  24.             exit(1);
  25.         }
  26.         wait(0);
  27.     }
  28.  
  29.  
  30.     printf("exiting...n");
  31.     return 0;
  32. }
  33.        
  34. warzaru@ubuntu:~/OS/UprocH$ ./exe a b c d
  35. fork: 0
  36. fork: 0
  37. fork: 1
  38. fork: 1
  39. fork: 1
  40. fork: 2
  41. fork: 2
  42. fork: 1
  43. fork: 2
  44. exiting...
  45. exiting...
  46. fork: 2
  47. exiting...
  48. exiting...
  49. fork: 2
  50. exiting...
  51. exiting...
  52. exiting...
  53. warzaru@ubuntu:~/OS/UprocH$ fork: 2
  54. fork: 2
  55. fork: 2
  56. exiting...
  57.        
  58. if(fork()==-1){} // first fork
  59. if(fork()==0){}  // second fork
  60.        
  61. pid = fork();
  62. if(pid == -1)
  63. {
  64.     ... //failed
  65. }
  66. else if(pid == 0)
  67. {
  68.     ... //success
  69. }
  70.        
  71. switch(fork())
  72. {
  73.     case -1:
  74.         ... // failed
  75.         break;
  76.     case 0:
  77.         ... // success
  78.         break;
  79. }