why this code doesn't work? I want that the code print the content of figlioA function if the number in input is even or print another code content in figlioB if the number in input is odd. What is wrong? Thank you!
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
int x;
void figlioA(int segnale) {
if (segnale == SIGUSR1)
printf("x=%d x^3=%d\n", x, (x * x * x));
}
void figlioB(int segnale) {
if (segnale == SIGUSR2)
printf("x=%d reciproco=1/%d\n", x, x);
}
int main(int argc, char * argv[]) {
int pidA, pidB;
int a, b;
x = atoi(argv[1]);
printf("Processo padre ppid=%d pid=%d\n", getppid(), getpid());
pidA = fork();
if (pidA == 0) { // figlio A
printf("figlio A ppid=%d pid=%d\n", getppid(), getpid());
a = getpid();
signal(SIGUSR1, figlioA);
pause();
} else
pidB = fork(); // crea il figlio B
if (pidB == 0) // figlio B
{
printf("figlio B ppid=%d pid=%d\n", getppid(), getpid());
b = getpid();
signal(SIGUSR2, figlioB);
pause();
}
if (pidA != 0 && pidB != 0) {
if (x % 2 == 0) {
kill(a, SIGUSR1);
}
if (x % 2 != 0) {
kill(b, SIGUSR2);
}
}
}
Best How To :
It seems to be a bug here:
if (pidA != 0 & pidB != 0) {
The correct should be "&&" and not "&":
if (pidA != 0 && pidB != 0) {
Edit: I got it working, for the kill function, As Chris Dodd said, you have to pass pidA and pidB, not a and b that are variables set in the child processes. You also need to initialize pidA and pidB to non-zero values, else process figlioA may enter in figlioB section after it have received the signal, you can also make the child processes return after pause()
. Here is the correct code, i added sleep(1) to let the time to the childs to proceed:
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
int x;
void figlioA(int segnale) {
if (segnale == SIGUSR1)
printf("x=%d x^3=%d\n", x, (x * x * x));
}
void figlioB(int segnale) {
if (segnale == SIGUSR2)
printf("x=%d reciproco=1/%d\n", x, x);
}
int main(int argc, char * argv[]) {
int pidA=1, pidB=1;
int a, b;
x = atoi(argv[1]);
printf("Processo padre ppid=%d pid=%d\n", getppid(), getpid());
pidA = fork();
if (pidA == 0) { // figlio A
printf("figlio A ppid=%d pid=%d\n", getppid(), getpid());
a = getpid();
signal(SIGUSR1, figlioA);
pause();
return 0;
} else pidB = fork(); // crea il figlio B
if (pidB == 0) // figlio B
{
printf("figlio B ppid=%d pid=%d\n", getppid(), getpid());
b = getpid();
signal(SIGUSR2, figlioB);
pause();
return 0;
}
sleep(1);
if (pidA != 0 && pidB != 0) {
if (x % 2 == 0) {
kill(pidA, SIGUSR1);
}
if (x % 2 != 0) {
kill(pidB, SIGUSR2);
}
}
}