Advertisement
Guest User

Untitled

a guest
Nov 18th, 2019
126
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1. #include <stdlib.h>
  2. #include <sys/types.h>
  3. #include <unistd.h>
  4. #include <stdio.h>
  5. #include <sys/stat.h>
  6. #include <fcntl.h>
  7.  
  8. void func0() {
  9. printf( "Fonction 0\n" );
  10. }
  11.  
  12. void func1() {
  13. printf( "Fonction 1\n" );
  14. }
  15.  
  16. void func2() {
  17. printf( "Fonction 2\n" );
  18. }
  19.  
  20. int forkn( void ( *array_ptrfunc[] )( void ), int nb_fils, pid_t *pid_array ) {
  21.  
  22. int child_done = 0;
  23. for ( int i = 0; i < nb_fils; i++ ) {
  24. pid_t fils = fork();
  25. if ( fils == 0 ) {
  26. array_ptrfunc[ i ]();
  27. exit( 0 );
  28. } else if ( fils > 0) {
  29. pid_array[ i ] = fils;
  30. child_done++;
  31. }
  32. }
  33. return ( child_done );
  34. }
  35.  
  36. #define NB_POINTERS 3
  37. int main( int argc, char** argv ) {
  38. int nb_fils = 3;
  39. pid_t ( *pid_array[NB_POINTERS]);
  40.  
  41. void ( *array_ptrfunc[] )() = { func0, func1, func2 };
  42. array_ptrfunc[ 0 ] = func0;
  43. array_ptrfunc[ 1 ] = func1;
  44. array_ptrfunc[ 2 ] = func2;
  45.  
  46. int res = forkn( &array_ptrfunc, nb_fils, &pid_array );
  47.  
  48. for ( int i = 0; i < 10; i++) {
  49. wait( pid_array[ i ] );
  50. }
  51.  
  52. printf( "Nombre de fils créés : %d\n", res );
  53.  
  54. return 0;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement