I dont understand why my code does not work.
This is my code. I don’t know why I’m get an error segment. Could somebody explain the reason to me?
#include <iostream> #include <string> #include <sys/types.h> #include <unistd.h> int id_process; void manager_signal () { kill (id_process, SIGKILL); kill (getppid(),SIGKILL); } int main () { id_process = fork (); if (id_process==-1) { perror('ERROR to create the fork'); } else { if ( id_process != 0 ) { printf('Father´s ID is %d \n', getpid()); alarm(5); (void) signal (SIGALRM, manager_signal); sleep (20); printf ('Running to where the father can be\n'); alarm (0); } else { printf ('CHildren´s ID is %d \n', getpid ()); for (;;) { printf ( 'Children RUN FOREVER ^^'); sleep (2); } } } return 0; }
Your question is a little difficult to understand since you don’t really explain what the error is, but I do have one question which I’m sure will be pertinent.
Why is the ‘father’ process killing its child and its parent? Shouldn’t it kill its child and itself (
id_processandgetpid()rather thangetppid()which is the parent PID)?That appears to be the problem. When I run that under Cygwin, it kills off my shell (darned annoying). If I change it to
kill (getpid(),SIGKILL);, it terminates okay after five seconds with the following output:This is with the program modified as follows: