NewFile
NewFile

Reputation: 531

C Programing : Parent & Child Process

I'm trying to figure this out, given the following code:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <string.h>

char mynum='0';
int main(void)
{
   int i;
   pid_t fork_return;
   static char buffer[10];
   fork_return = fork();
   if (fork_return == 0)
   {
      strcpy(buffer, "CHILD"); /*in the child process*/
      for (i=0; i<5; ++i) /*both processes do this*/
      {
         mynum=i + '0';
         sleep(1); /*5 times each*/
         write(1, buffer, sizeof(buffer));
         write(1, &mynum, 1);
         write(1, "\n", 1);
      }
      return 0;
   }
   else
   {
      strcpy(buffer, "PARENT"); /*in the parent process*/
      for (i=0; i<5; ++i) /*both processes do this*/
      {
         sleep(1); /*5 times each*/
         write(1, buffer, sizeof(buffer));
         write(1, &mynum, 1);
         write(1, "\n", 1);
      }
      return 0;
   }
} 

Notice that mynum is a global variable.

Why does child print CHILD0, CHILD1, CHILD2, etc whereas parent prints PARENT0, PARENT0, PARENT0, etc? Remember mynum is a global variable.

Also, if I fork a process, how come when I print their pid, their ppid are always the same?

Upvotes: 2

Views: 518

Answers (2)

jxh
jxh

Reputation: 70402

The parent and child processes have separate virtual address spaces. Thus, an update to the global variable in the child process does not affect the global variable in the parent process. This is a feature known as memory protection, where memory allocated for one process is typically not accessible by a different process.

The pid, retrieved with getpid(), is the the process id of the process and each process has a unique one. The ppid, retrieved with getppid(), is the parent process id. So long as the parent is alive, the parent process id will be the pid of the parent process from which the child was fork()d. When a child process's parent dies, the child gets inherited by the init process, which has process id 1.

Upvotes: 1

Rift
Rift

Reputation: 86

Because it doesn't matter if it's global variable, you use them in separate processes.

Upvotes: 1

Related Questions