Hi,
First off I am doing homework. I have been looking at this site to view code examples, and I am happy to see the technical caliber on these forums. This is the first time I am programming with signals and I must say that I am "familiar" at best when coding with them.
My assignment is to sync a parent and a child using signals. I have got that to work (sort of). But the output is quite strange. Anyhow, if anyone can tell me if I am using signals right, and if anyone could explain why I am getting this crazy output, would be awesome.
Thanks!
code file w8.c:
Code:
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <sys/wait.h>
void mySignalHandler(int sig);
void sigParent(void);
void sigChild(void);
int wait_status;
pid_t parentPid, childPid, pid;
int main()
{
int i;
wait_status = 1;
pid = fork();
switch(pid)
{
case -1: /* an error occurred */
printf("Fork error\n");
break;
case 0: /* this code is executed by the child process */
childPid = getpid();
signal(SIGCONT, mySignalHandler);
signal(SIGSTOP, mySignalHandler);
for(i=1; i<10; i++)
{
if(wait_status == 0)
{
waitpid(parentPid, NULL, WUNTRACED);
}
else
{
printf("Child process, iteration: %d\n", i);
sigParent();
}
}
break;
default: /* this code is executed by the parent process */
parentPid = getpid();
signal(SIGCONT, mySignalHandler);
signal(SIGSTOP, mySignalHandler);
for(i=1; i<10; i++)
{
if(wait_status == 0)
{
waitpid(childPid, NULL, WUNTRACED);
}
else
{
printf("Parent process, iteration: %d\n", i);
sigChild();
}
}/*end for*/
break;
} /*end switch*/
}/*end main*/
void mySignalHandler(int sig)
{
if(sig == SIGSTOP)
wait_status = 0;
else if(sig == SIGCONT)
wait_status = 1;
}
void sigParent(void)
{
kill(parentPid, SIGCONT);
raise(SIGSTOP);
}
void sigChild(void)
{
kill(childPid, SIGCONT);
raise(SIGSTOP);
}
and then the output looks like this. Its not always the same either. But it does always say signal suspended:
Code:
Parent process, iteration: 1
Child process, iteration: 1
Parent process, iteration: 2
Child process, iteration: 2
Parent process, iteration: 3
Child process, iteration: 3
Parent process, iteration: 4
Child process, iteration: 4
Parent process, iteration: 5
Suspended (signal)
Child process, iteration: 5
Parent process, iteration: 6
Child process, iteration: 6
Parent process, iteration: 7
Child process, iteration: 7
Parent process, iteration: 8
Child process, iteration: 8
Parent process, iteration: 9
Child process, iteration: 9
[8] + Suspended (signal) ./a.out