I'm doing a work for school, this example works on a Linux machine. I'm trying it on my Mac but it doesn't work, and as I know this should work but I can't figure out why.
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <time.h>
#include <unistd.h>
struct sigaction act_fils, act_pere;
int pid;
void fonction_fils(){
printf("Temperature : %d", rand() % 31 10);
fflush(stdout);
}
void fonction_pere(){
kill(pid,SIGUSR1); // Permet d'envoyer un signal au fils
alarm(5);
}
int main(){
srand(time(NULL));
pid=fork();
if (pid==0){
act_fils.sa_handler= fonction_fils();
sigaction(SIGUSR1, &act_fils, NULL);
while(1) {
pause();
}
}
else{
act_pere.sa_handler=fonction_pere();
sigaction(SIGALRM, &act_pere, NULL);
alarm(5);
while(1){
sleep(1);
printf("-");
fflush(stdout);
}
}
return 0;
}
And this is the error "cannot assign a value of type "void" to an entity of type "void (*)(int)" " on the sa_handler. Can you help me plz ? Thanks a lot !
CodePudding user response:
Firstly, when your program is preparing the binding of signal handler, it is not not calling the function at that time.
You want to obtain the function itself as a pointer object, and store that, without calling the function:
act_fils.sa_handler= fonction_fils; // no function call () parentheses
Secondly, the function has to have the right type for a signal handler:
void fonction_fils(int sig)
{
}
Note that in the C language, unlike C , if you declare a function paramter list as ()
, it declares the function as having an unknown parameter type information. The function definition is one that takes no arguments, compatible with (void)
, but as a declaration it doesn't say that to the surrounding program.
CodePudding user response:
Instead of statements like these
act_fils.sa_handler= fonction_fils();
and
act_pere.sa_handler=fonction_pere();
where there are used function calls that have the return type void you need to write
act_fils.sa_handler= fonction_fils;
and
act_pere.sa_handler=fonction_pere;
to assign function pointers.
Pay attention to that for example the data member sa_handler
has the type
void (*sa_handler)(int);
So the corresponding function shall have the same type.