Thread: fork() and signal()

  1. #1
    Registered User
    Join Date
    Dec 2002
    Posts
    13

    fork() and signal()

    Hello
    I have got a code from my professor:

    Code:
    #include <unistd.h>
    #include <stdio.h>
    #include <signal.h>
    
    int v[3] = {0, 0, 0};
    
    static void handler(int sig) 
    {
      v[0]++;
    }
    
    int main()
    {
      int pid, pid1, pid2;
      signal(SIGUSR1, handler);
    
      pid = getpid();
      pid1 = fork();
      
      if (pid1) pause();
      else sleep(1);
    
      pid2 = fork();
    
      if (pid2) sleep(1);
      if (pid1 == 0) v[1]++;
      if (pid2 == 0) v[2]++;
      if (getppid() == pid) kill(pid, SIGUSR1);
    
      printf("%d %d %d %d\n", v[0], v[1], v[2], getpid());
      return 0;
    }
    result:
    0 1 1 4396
    0 1 0 4395
    1 0 1 4397
    2 0 0 4394

    I understand the order of output and the first line of the output, but then, I don`t understand the result.
    process 4396 increment v[1] and v[2] and process 4395 v[1] too. so for me the result is 021 in line two.
    i hope, somebody can helps me.
    thank you
    regards

    sphreak

  2. #2
    Registered User
    Join Date
    Dec 2002
    Posts
    13
    hello
    i have found the solution. i thought v[3] is global, but every process has his own.
    sry for this thread
    regards
    sphreak

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Understanding fork()
    By NuNn in forum C Programming
    Replies: 8
    Last Post: 02-27-2009, 12:09 PM
  2. Replies: 3
    Last Post: 10-15-2008, 09:24 AM
  3. signal sending and waiting
    By eva69 in forum Linux Programming
    Replies: 1
    Last Post: 10-03-2008, 05:07 PM
  4. Signals, fork(), wait() and exec()
    By DJTurboToJo in forum C Programming
    Replies: 7
    Last Post: 03-18-2008, 09:14 AM
  5. process programming
    By St0rM-MaN in forum Linux Programming
    Replies: 2
    Last Post: 09-15-2007, 07:53 AM