10 Haziran 2015 Çarşamba

Linux Parent and Child Process - Fork Function

Function fork()

#include <unistd.h>
pid_t fork(void);

fork() creates a new process by duplicating the calling process. The new process has its own identifier. It also has its own data space, which is a copy of their relevants from the parent process.

Functions getpid(), getppid()

#include <unistd.h>
pid_t getpid(void);
pid_t getppid(void);

The functions getpid() and getppid() return own identifier (PID) of the caller
ID and a parent ID.


#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char** argv)
{
  pid_t child_pid;
  char *message;
  printf("So far only one process is runing\n");
  child_pid = fork();
  switch (child_pid)
  {
  case -1:
    printf("fork process failed\n"); // if it's failed
    exit(1);
  case 0:
    message = "I am a child"; // Child process is working

  break;
  default:
    message = "I am a parent"; // Parent process is working
   
  break;
  }
for (; ; ) // infinite loop you can break with interrupt signal (ctrl + c )
{
puts(message);
sleep(2);
}
}

Hiç yorum yok:

Yorum Gönder

Yorum yaptığınız için teşekkür ederiz.