How to return a signal from child process and how to set an alarm?

Please see the following question,


Write a program that creates a child process using fork (). The child prints its parent’s name, Parent ID and Own ID while the parent waits for the signal from the child process. Parent sets an alarm 10 seconds after the Child termination.


And see this code I made,


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <unistd.h> 
#include <sys/wait.h> 
#include <stdio.h>
using namespace std;

int main()
{
int pid, status; 
pid = fork(); 
if (pid == 0)
{
cout << "I am child, my id is " << getpid() << endl;
cout << "I am parent, my id is " << getppid() << endl; 
}
else 
{
wait(&status); 
if (WIFSIGNALED(status))
{
cout << "Child process terminated. Setting alarm of 10 seconds" << endl;
alarm(10); 
}
cout << "Process is terminating" << endl;
}
return 0; 
}


This isn't working because WIFSIGNALED never returns 1... If I try WIFEXITED then it returns 1, but from my understanding, unless I write
 
exit(0); 

the WIFEXITED shouldn't return 1 and instead WIFSIGNALED should return 1... However, whether I write exit(0) or not, WIFEXITED still returns 1..

How do I make WIFSIGNALED to return 1?

And also, what does the alarm command do and how do I set up an alarm in linux? Please help, thank you!
Last edited on
If you want the parent to see WIFSIGNALED, then the child has to raise one of the "Term" signals that causes a process to exit with a signal.

Alarms raise the SIGALRM signal within the process.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <unistd.h>
#include <sys/wait.h>
#include <stdio.h>
#include <signal.h>
#include <string.h>
using namespace std;

// Be careful what you call in signal handlers.
// http://www.man7.org/linux/man-pages/man7/signal-safety.7.html
void handler(int sig) {
  const char *buff = "Alarm went off\n";
  write(1,buff,strlen(buff));
}

int main()
{
  int pid, status;
  pid = fork();
  signal(SIGALRM,handler);
  if (pid == 0) {
    cout << "I am child, my id is " << getpid() << endl;
    cout << "I am parent, my id is " << getppid() << endl;
    raise(SIGINT);
  } else {
    wait(&status);
    if (WIFSIGNALED(status)) {
      cout << "Child process terminated. Setting alarm of 10 seconds" << endl;
      alarm(10);
    }
    cout << "Process is terminating" << endl;
  }
  cout << "Press Q-enter after 20 seconds";
  char c;
  cin >> c;
  return 0;
}
while the parent waits for the signal from the child process
Maybe this is just a sloppy way of saying "the parents waits for the child to exit." In other words, maybe "signal" doesn't really a UNIX signal, but the more general sense of "the child indicates to the parent that it's done."
Topic archived. No new replies allowed.