What does the following C program print and why? Note that emphasis of this ques
ID: 3819605 • Letter: W
Question
What does the following C program print and why? Note that emphasis of this question is on your understanding of the signal functionality. State your assumptions where necessary.
pid_t pid;
void h1(int sig) {
printf("eagle");
kill(pid, SIGUSR2);
}
void h2(int sig) {
printf("sparrow");
exit(0);
}
main() {
signal(SIGUSR2, h1);
if ((pid = fork()) == 0) {
signal(SIGUSR2, h2);
kill(getppid(), SIGUSR2);
while(1) {};
}
else {
pid_t p; int status;
if ((p = wait(&status)) > 0) {
printf("pigeon");
}
}
}
Explanation / Answer
Output for this program will be
sparroweaglepiegon
Explanation:-
In this first the execution starts with the main function.
When the execution starts it first comes to the function signal(SIGUSR2,h1) then the execution comes to the if statement, because in the starting there is no signal there will be no child process need to be created i.e. fork = 0 only so the next signal(SIGUSR2,h2) now the signal is passed to the h2 function then now sparrow is get printed.
Now the execution comes to the while condition because of this it again goes to h1 function and then eagle gets printed . Then now the if condition fails as the signal got initiated so the condition fails and then else block is get initiated then the pigeon is printed
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.