I have to code a simple C application that creates a process and a child (fork()) and I have to do an operation. Parent initializes the values and child calculates. I write this:
#include <stdlib.h>
#include <signal.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
typedef struct {
int op1;
char op;
int op2;
} Operation;
Operation *varOP;
void finalResult()
{
float result = 0;
if(varOP->op == '+') result = (varOP->op1 + varOP->op2);
if(varOP->op == '-') result = (varOP->op1 - varOP->op2);
if(varOP->op == '*') result = (varOP->op1 * varOP->op2);
if(varOP->op == '+') result = (varOP->op1 / varOP->op2)
printf("%f",result);
}
int main () {
int p;
varOP = (Operation *)malloc(sizeof(Operation));
p = fork();
if(p == 0) // If child
{
signal(SIGUSR1, finalResult );
pause();
}
if(p > 0) // If parent
{
varOP->op = '+';
varOP->op1 = 2;
varOP->op2 = 3;
kill(p, SIGUSR1);
wait(NULL);
}
return 0;
}
But my child is never called. Is there something wrong with my code?
Thanks for your help!
Your sample code also has a more fundamental problem: each process has its own data space, and so your technique of sending information to the child via the heap will not work. One solution is to use a pipe. This adds only four more lines to your code: