Please write down the C pseudo-code for the following program: The program first
ID: 3832045 • Letter: P
Question
Please write down the C pseudo-code for the following program:
The program first creates a child process CP. So, there are two processes.
The parent process does the following:
1. Create a thread CT. The thread CT outputs "I am a thread", then terminates;
2. Send SIGHUP signal to the child process CP.
The child process CP does the following:
1. Specify the action associated with signal SIGHUP. That is, when the child process CP receives SIGHUP, CP outputs "I have received SIGHUP";
2. Infinite loop.
Explanation / Answer
Code:
#include<pthread.h>
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include <signal.h>
void sighup(int signo) {
signal(SIGHUP,sighup); /* reset signal */
printf("CHILD: I have received a SIGHUP ");
}
void* childThread(void *arg)
{
printf(" I am a thread ");
}
int main()
{
int status;
int cp;
int thread;
cp=fork();
pthread_t ct;
// Create the thread
thread = pthread_create(&ct, NULL, &childThread, NULL);
if (thread != 0)
printf(" can't create thread :[%s]", strerror(thread));
else
printf(" Thread created successfully ");
// Child process section
signal(SIGHUP,sighup); /* set function calls for signal*/
if(cp<0)
{
printf(" Error ");
exit(1);
}
else if(ct==0)
{
signal(SIGHUP,sighup); /* set function calls */
for(;;); /* loop for ever */
}else{
signal(SIGHUP, SIG_DFL);
printf(" PARENT: sending SIGHUP ");
kill(cp,SIGHUP);
sleep(3); /* pause for 3 secs */
}
}