分布式架构

fork之前的缓冲区问题

2019-06-11  本文已影响0人  perryn

fork 系统调用

Description

代码例子

/*************************************************************************
  > File Name: fork0.c
  > Author:perrynzhou 
  > Mail:perrynzhou@gmail.com 
  > Created Time: Tue 11 Jun 2019 10:27:20 AM CST
 ************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <ctype.h>
#include <unistd.h>
#include <getopt.h>
void usage(char *s)
{
  printf("%s -f {0 | 1}\n", s);
  printf("   1  -- force flush all opened stream before fork\n");
  printf("   0  -- not flush all opened stream before fork\n");
}
bool is_number(const char *s)
{
  if (s == NULL)
  {
    return false;
  }
  while (*s != '\0')
  {
    if (isdigit(*s++) == 0)
    {
      return false;
    }
  }
  return true;
}
int main(int argc, char *argv[])
{
  if (argc != 3)
  {
    usage(argv[0]);
    exit(0);
  }
  const char *cmd_parse_fmt = "f:";
  char ch;
  int force_flush_flag = 0;
  while ((ch = getopt(argc, argv, cmd_parse_fmt)) != -1)
  {
    switch (ch)
    {
    case 'f':
      if (!is_number(optarg))
      {
        force_flush_flag = -1;
      }
      else
      {
        force_flush_flag = atoi(optarg);
      }
      break;
    default:
      break;
    }
  }
  if (force_flush_flag > 1 || force_flush_flag < 0)
  {
    usage(argv[0]);
    exit(0);
  }
  printf("flush opened stream :%d\n", force_flush_flag);

  printf("[%ld]begin\n", getpid());
  pid_t pid;
  if (force_flush_flag == 1)
  {
    fflush(NULL);
  }
  if ((pid = fork()) < 0)
  {
    perror("fork");
    exit(0);
  }
  else if (pid == 0)
  {
    printf("[%ld] child process working\n", getpid());
    exit(0);
  }
  else
  {
    printf("[%ld] parent process working\n", getpid());
  }
  return 0;
}

标准输出

image.png

文件输出

image.png

标准输出和文件输出

上一篇 下一篇

猜你喜欢

热点阅读