Forum Home
Press F1
 
Thread ID: 124590 2012-05-05 10:13:00 C signals (Linux) pcuser42 (130) Press F1
Post ID Timestamp Content User
1273759 2012-05-05 10:13:00 For an assignment question, I need to write a C program involving signals. I'm pretty sure I've done it corectly, yet the child process isn't getting the signal from the parent process, but goes to standard output just fine. :confused: :rolleyes:


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>

FILE *readEnd;
FILE *writeEnd;

void sigInt(int SIGNO) {
printf("%i - in the keyboard interrupt signal handler\n", getppid());
}

void userSig(int SIGNO) {
printf("User specific handler");
//printf("%i - in the user specific signal handler\n", getpid());
}

void parentsCode(int childsPID) {
printf("parent: %i\n", getppid());
signal(SIGINT, sigInt);
pause();
system("ps");
printf("%i - awoke from a pause, sending a SIGUSR1 signal to the child\n", getppid());
kill(childsPID, SIGUSR1);
char buffer[80];
fgets(buffer, 80, readEnd);
printf("%i - received %s from the child", getppid(), buffer);

}

void childsCode(void) {
signal(SIGUSR1, userSig);
printf("child: %i\n", getpid());
pause();
printf("%i - awoke from a pause, about to write to the pipe\n", getpid());
fprintf(writeEnd, "Hi Mum");
fflush(writeEnd);
}

int main(void) {
int childsPID;
int pipefd[2];
char buffer[80];

system("ps"); // execute the “ps” command
pipe(pipefd);

writeEnd = fdopen(pipefd[1], "w");
fprintf(writeEnd, "Hello from process %d\n", getpid());
fflush(writeEnd);

readEnd = fdopen(pipefd[0], "r");
fgets(buffer, 80, readEnd);
printf("\n%s\n", buffer);

if ((childsPID = fork())) {
//printf("Child PID from parent: %i", childsPID);
parentsCode(childsPID);
} else {
childsCode();
}
return EXIT_SUCCESS;
}

(The program execues "ps" then spawns a child process. The parent process waits for Ctrl+C to be typed - this signal works fine - then sends a signal to the child process. The child then writes to a pipe which the parent reads from.)
pcuser42 (130)
1273760 2012-05-05 10:41:00 Is this ( www.google.co.nz) what you mean? stratex5 (16685)
1273761 2012-05-05 10:54:00 Is this ( www.google.co.nz) what you mean?

The first signal handler works fine, it's just the second one that's broken. ;)
pcuser42 (130)
1