C++编程分布式架构

zombies 和 init process

2019-06-16  本文已影响1人  perryn

进程关系

zombies进程

孤儿进程

zombies 代码例子

image.png
/*************************************************************************
  > File Name: fork0.c
  > Author:perrynzhou 
  > Mail:perrynzhou@gmail.com 
  > Created Time: Sun 16 Jun 2019 01:55:54 PM CST
 ************************************************************************/

#include <stdio.h>
#include <getopt.h>
#include <ctype.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int is_num(const char *s)
{
  if (NULL == s)
  {
    return -1;
  }
  size_t len = strlen(s);
  for (int i = 0; i < len; i++)
  {
    if (isdigit(s[i]) == 0)
    {
      return -1;
    }
  }
  return 0;
}
int main(int argc,char *argv[])
{
  int pn, fn;
  int default_pn = 2;
  const char *cmd_line = "p:";
  char ch;
  while ((ch = getopt(argc, argv, cmd_line)) != -1)
  {
    int flag = is_num(optarg);
    switch(ch)
    {
    case 'p':
      pn = (flag == 0) ? atoi(optarg) : default_pn;
      break;
    default:
      break;
    }
  }
  fprintf(stdout,"process number:%d\n",pn);
  fflush(NULL);
  for (int i = 0; i < pn; i++)
  {
    fflush(NULL);
    pid_t pid = fork();
    if (pid == -1)
    {
      perror("fork()");
      exit(1);
    }
    if (pid == 0)
    {
      fprintf(stdout, "child process %ld,parent process %ld\n", getpid(), getppid());
      //sleep(100000); 
      exit(0);
    }
  }
  sleep(10000);
  exit(0);
  return 0;
}
孤儿进程
image.png
/*************************************************************************
  > File Name: fork0.c
  > Author:perrynzhou 
  > Mail:perrynzhou@gmail.com 
  > Created Time: Sun 16 Jun 2019 01:55:54 PM CST
 ************************************************************************/

#include <stdio.h>
#include <getopt.h>
#include <ctype.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int is_num(const char *s)
{
  if (NULL == s)
  {
    return -1;
  }
  size_t len = strlen(s);
  for (int i = 0; i < len; i++)
  {
    if (isdigit(s[i]) == 0)
    {
      return -1;
    }
  }
  return 0;
}
int main(int argc,char *argv[])
{
  int pn, fn;
  int default_pn = 2;
  const char *cmd_line = "p:";
  char ch;
  while ((ch = getopt(argc, argv, cmd_line)) != -1)
  {
    int flag = is_num(optarg);
    switch(ch)
    {
    case 'p':
      pn = (flag == 0) ? atoi(optarg) : default_pn;
      break;
    default:
      break;
    }
  }
  fprintf(stdout,"process number:%d\n",pn);
  fflush(NULL);
  for (int i = 0; i < pn; i++)
  {
    fflush(NULL);
    pid_t pid = fork();
    if (pid == -1)
    {
      perror("fork()");
      exit(1);
    }
    if (pid == 0)
    {
      fprintf(stdout, "child process %ld,parent process %ld\n", getpid(), getppid());
      sleep(100000); 
      exit(0);
    }
  }
 // sleep(10000);
  exit(0);
  return 0;
}
上一篇下一篇

猜你喜欢

热点阅读