Here's an example in C using fork().
Code:
#include <sys/types.h>
#include <sys/wait.h>
#include "errors.h"
int main (int argc, const char * argv[]) {
int exit_code ;
pid_t pid ;
while(1) {
printf("After you press ENTER to start the loop, enter -1 at anytime to quit...\n") ;
getchar() ;
int counter = 0 ;
pid = fork() ;
if (pid == (pid_t)-1) errno_abort("Fork") ;
if (pid == (pid_t) 0) { // in the child
while(1) {
counter++ ;
if ((counter % 1000)==0) printf("%d\n", counter) ;
}
}
else { // in the parent, wait for user to enter -1.
do {
scanf( "%d", &exit_code) ;
} while (exit_code != -1 ) ;
// Kill the child process
printf("Killing child process %d...\n", (int) pid) ;
kill(pid , SIGTERM) ;
sleep(1) ;
printf("Child killed. Exiting.\n") ;
exit(0) ;
}
}
return 0;
}
errors.h
Code:
/*
* errors.h
*
*
*/
#ifndef __errors_h
#define __errors_h
#include <unistd.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef DEBUG
#define DPRINTF(arg) printf arg
#else
#define DPRINTF(arg)
#endif
#define err_abort(code,text) \
do { \
fprintf(stderr, "%s at \"%s\":%d: %s\n", \
abort() ; \
} while (0)
#define errno_abort(text) \
do { \
fprintf(stderr, "%s at \"%s\":%d: %s\n", \
text, __FILE__, __LINE__, strerror(errno)) ; \
abort() ; \
} while (0)
#endif
Todd