Messi anlcuni nuovi esempi. E messa la GPL negli esempi.
[gapil.git] / sources / ForkTest.c
1 /****************************************************************
2  *
3  * Program ForkTest.c: 
4  * Program to test process creation
5  *
6  * Author: Simone Piccardi
7  * Sep. 2001
8  *
9  * Usage: forktest -h give all info's
10  *
11  * $Id: ForkTest.c,v 1.1 2001/09/09 17:39:15 piccardi Exp $
12  *
13  ****************************************************************/
14 /* 
15  * Include needed headers
16  */
17 #include <errno.h>       /* error definitions and routines */ 
18 #include <stdlib.h>      /* C standard library */
19 #include <unistd.h>      /* unix standard library */
20 #include <stdio.h>       /* standard I/O library */
21 #include <string.h>      /* string functions */
22
23 /* Help printing routine */
24 void usage(void);
25
26 int main(int argc, char *argv[])
27 {
28 /* 
29  * Variables definition  
30  */
31     int i;
32     int nchild;
33     pid_t pid;
34     /*
35      * Input section: decode command line parameters 
36      * Use getopt function
37      */
38     opterr = 0;  /* don't want writing to stderr */
39     while ( (i = getopt(argc, argv, "h")) != -1) {
40         switch (i) {
41         /* 
42          * Handling options 
43          */ 
44         case 'h':  
45             printf("Wrong -h option use\n");
46             usage();
47             return(0);
48             break;
49         case '?':   /* unrecognized options */
50             printf("Unrecognized options -%c\n",optopt);
51             usage();
52         default:    /* should not reached */
53             usage();
54         }
55     }
56     /* ***********************************************************
57      * 
58      *           Options processing completed
59      *
60      *                Main code beginning
61      * 
62      * ***********************************************************/
63     /* There must be remaing parameters */
64     if (optind == argc) {
65         usage();
66     }
67     nchild = atoi(argv[optind]);
68     printf("Test for forking %d child\n", nchild);
69     /* loop to fork children */
70     for (i=0; i<nchild; i++) {
71         if ( (pid = fork()) < 0) {
72             printf("Error on %d child creation, %s\n", i, strerror(errno));
73         }
74         if (pid == 0) {   /* child */
75             printf("Child %d successfully executing\n", i++);
76             sleep(2);
77             printf("Child %d exiting\n", i);
78             exit(0);
79         } else {          /* parent */
80             printf("Spawned %d child, pid %d \n", i, pid);
81         }
82     }
83     /* normal exit */
84     return 0;
85 }
86 /*
87  * routine to print usage info and exit
88  */
89 void usage(void) {
90     printf("Program forktest: fork a given number of child \n");
91     printf("Usage:\n");
92     printf("  forktest [-h] child to fork \n");
93     printf("  -h           print this help\n");
94     exit(1);
95 }