0

I'm trying to write a small program that generates a child process with fork() that will have to increase a variable shared with the parent, how do I share an unsigned int variable?

code:

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>

static unsigned int elapsed;

int count(){
    while(1){
        sleep(1);
        elapsed++;
    }
    exit(EXIT_SUCCESS);
}

void hadler(int sig){
    if( sig == SIGUSR1){
        printf("elapsed: %u\n", elapsed);
    }

}

int main(){
    pid_t pid = getpid();
    printf("This is my pid: %d\n", pid);
    pid = fork();
    if(pid == 0)
        count();

    while(1){
        signal(SIGUSR1, hadler);
    }
}

You can see there is a child than exec count() (increase a variable "elapsed" every second). The parent is waiting for SIGUSR1, when receive the signal he print the "elapsed". Naively I tried to use a static global variable but it doesn't work for obvious reasons.

Phocs
  • 2,430
  • 5
  • 18
  • 35
  • 7
    There are many ways of doing [Inter-Process Communications (IPC)](https://en.wikipedia.org/wiki/Inter-process_communication). Read about them, search for how they are implemented in a POSIX (Unix, Linux, macOS) environment, and experiment. – Some programmer dude May 17 '17 at 17:28
  • Possible duplicate of [C, how to use POSIX semaphores on forked processes?](http://stackoverflow.com/questions/16400820/c-how-to-use-posix-semaphores-on-forked-processes) – Cloud May 17 '17 at 17:49
  • You can pipes to communicate between the processes. Pipes are very simple and standard way to communicate between the two processes. – yadhu May 18 '17 at 00:35
  • Isn't thinks asking for an atomic? – Persixty May 19 '17 at 13:04
  • there are a number of system functions that are NOT to be placed in a signal handler, `printf()` is one of the system functions to NOT use. Suggest having the signal handler function set a variable. Then have the main function be checking/polling that variable, when the variable is set, then call `printf()` and unset the variable. (actually safer to have the signal handler increment the variable, have the main() checking for when the variable changes, then decrement the variable and call `printf()` – user3629249 May 21 '17 at 13:48

0 Answers0