stumped
stumped

Reputation: 3293

Confusion with forking and global variables

Why does printing on line 22 result in 1 instead of 3? count is a global variable and it was already modified in handlerA, so why didn't it retain its value on line 21 and 22?

1    pid_t pid;
2    int count = 0;
3    
4    void handlerA(int sig) {
5        count += 2
6        printf("count = %d\n", count);
7        fflush(stdout);
8        kill(pid, SIGUSR1);
9    }
10
11   void handlerB(int sig) {
12       count += 3;
13       printf("count = %d\n", count);
14       fflush(stdout);
15       exit(0);
16   } 
17
18  int main() {
19     signal(SIGUSR1, handlerA);    
20     if ((pid = fork()) == 0) {
21          count++;
22          printf("count = %d\n", count);
23          fflush(stdout);
24          signal(SIGUSR1, handlerB);
25          kill(getpid(), SIGUSR1);
26          while (1) {};
27     }
28     else {
29          wait();
30          count += 4;
31          printf("count = %d\n", count);
32          fflush(stdout);
33     }
34     return 0; 
35   }

Upvotes: 0

Views: 69

Answers (1)

James Taylor
James Taylor

Reputation: 6258

I think the confusion is stemming from signal(): it's a function that is simply setting the handlerA to handle SIGUSR1.

The signal is not being invoked nor are any of the handlers triggered in any way by the time line 22 is reached. So the program calls fork() and count increments from 0 to 1, like expected.

You would see the behavior you're expecting if you also kill(pid, SIGUSR1); in main somewhere before the fork.

Don't re-raise the signal inside of that signal's respective handler.

Upvotes: 4

Related Questions