/* alarm2.cpp an alarm example using multiple process */ #include #include #include #include int main(int argc, char *argv[]) { pid_t pid; int seconds; char line[128]; char message[64]; while(1) { printf("Alarm>"); if (fgets(line, sizeof (line), stdin) == NULL) exit(0); if (strlen (line) <=1) continue; /* parse input line into seconds (%d) and a message * (%64[^\n]), consisting of up to 64 characters * separated from the seconds by whitespace. */ if (sscanf(line, "%d %64[^\n]", &seconds, message ) <2 ) { fprintf( stderr, "Bad Command\n"); } else { pid = fork(); if (pid == (pid_t) -1 ) { printf("fork() error!\n"); exit(1); } if ( pid == (pid_t)0) { /* this is the child, wait and then print a message */ sleep (seconds); printf( "(%d) %s\n", seconds, message); exit(0); } else { /* this is parent, call waitpid() to collect children * that have already terminated. */ do { pid = waitpid ((pid_t) -1, NULL, WNOHANG); if (pid == (pid)-1) { printf("Wait for child!\n"); exit(1); } }while( pid != (pid_t) 0); } } } }