2

My child proccess can't start to work. I need to pass signal and execute readUsual function.

This is a small piece of code:

int main() { pid_t pid2 = fork(); if (pid2 < 0) printf("Can't create child process\n"); else if (pid2==0) { //this block never execute printf("Process2, pid=%d\n",getpid()); signal(SIGUSR1,readUsual); } else { kill(pid2,SIGUSR1); printf("%s\n","Proccess1 end"); for(;;); } return 0; } 

1 Answer 1

6

You need to either add synchronization in some way, or call signal() before your fork().

With your current code, you have no way to be sure child process call signal() before it receive the signal. Receiving the signal before the instruction to handle it will stop the child process.

Example:

#include <stdio.h> #include <sys/types.h> #include <signal.h> #include <unistd.h> static int received = 0; void readUsual(int sig) { if (sig == SIGUSR1) { received = 1; } } int main() { signal(SIGUSR1,readUsual); pid_t pid2 = fork(); if (pid2 < 0) printf("Can't create child process\n"); else if (pid2==0) { printf("Process2, pid=%d\n",getpid()); while (!received) ; printf("SIGUSR1 received.\n"); } else { kill(pid2,SIGUSR1); printf("%s\n","Proccess1 end"); while (1) ; } return 0; } 

Example of output with this code:

Process1 end Process2, pid=1397 SIGUSR1 received 
Sign up to request clarification or add additional context in comments.

2 Comments

Thou shalt not printf from a signal handler.
@alk I did not know, currently DuckDuckGoing it.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.