論壇首頁 編程語言技術論壇

C: Linux C 編程 - fork

瀏覽 195 次
精華帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隱藏帖 (0)
作者 正文
   發表時間:2020-08-26  

fork

fork是和進程相關的一個概念。在程序中可以通過fork可以創建一個進程。

?

這樣進程就存在父子關系。創建子進程的進程為父進程,被創建的進程為子進程。

?

先從一個最簡單的fork子進程例子開始:

#include <stdio.h>
#include <unistd.h>
void main() 
{
  pid_t pid = fork();
  if (pid == 0)
  {
	printf("child process.\n");
  }
  else 
  {
    printf("parent process.\n");
  }
}

在上面這個最簡單的fork子進程例子中,fork是一個系統調用,fork函數調用后將創建一個子進程。從上面的例子可以看出,想要創建一個子進程很簡單,基本只需要幾行代碼。

?

核心代碼:

?

pid_t pid = fork();
if (pid == 0) {
  printf("child process.\n");
} else {
  printf("parent process.\n");
}

?

?

#include <stdio.h>
#include <stdlib.h>

#include <sys/types.h>
#include <unistd.h>
#include <errno.h>

void fn() 
{
  int i;
  for (i = 0; i < 100; i++)
  {
	fprintf(stdout, "[ INFO][%04d][%04d] i=%d\n", getppid(), getpid(), i);
  }
}

void TRACE_FORK(pid) 
{
  #ifdef __TRACE_FORK   
    fprintf(stdout, "[ INFO][%04d][%04d] child process forked. pid: %d\n", getppid(), getpid(), pid);                     
  #else                 
    if (pid == 0)       
    {                   
      fprintf(stdout, "[ INFO][%04d][%04d] child process forked. in child process, pid: %d\n", getppid(), getpid(), pid); 
    }                   
    else                
    {                   
      fprintf(stdout, "[ INFO][%04d][%04d] child process forked. pid: %d\n", getppid(), getpid(), pid);                  
    }                  
  #endif        
}

void main() 
{
  pid_t pid;
  fprintf(stdout, "[ INFO][%04d][%04d] main\n", getppid(), getpid());

  pid = fork();
  if (pid == -1)
  {
	fprintf(stderr, "[ERROR][%04d][%04d] fork error, errno: %d\n", getppid(), getpid(), errno);
	return;
  }

  TRACE_FORK(pid);

  if (pid == 0)
  {
	// in child process
	fn();
    //exit(0);
  }
  else 
  {
    fn();
  }
}

?

fork

?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <assert.h>

#include <sys/types.h>
#include <sys/socket.h>

#include <netinet/in.h>
#include <arpa/inet.h>

#include <unistd.h>
#include <fcntl.h>

typedef struct p_worker 
{
    pid_t pid;
    int index;	
} p_worker_t;


int stop = 0;

int max_worker_process_num = 32;


int _socket_setnonblock(int fd) 
{
    int flags = fcntl(fd, F_GETFL);
    if (flags == -1) 
    {
        printf("fcntl error %d\n", errno);
				return -1;
    }

    flags |= O_NONBLOCK;
    if (fcntl(fd, F_SETFL, flags) == -1)
    {
        printf("fcntl error %d\n", errno);
				return -1;
    }
    return 0;
}

int socket_setnonblock(int fd) 
{
    int flags = fcntl(fd, F_GETFL);
    if (flags == -1) 
    {
        printf("fcntl error %d\n", errno);
				return -1;
    }

    flags |= O_NONBLOCK;
    if (fcntl(fd, F_SETFL, flags) == -1)
    {
        printf("fcntl error %d\n", errno);
				return -1;
    }
    return 0;
}

int _socket(int domain, int type, int protocol)
{
    return socket(domain, type, protocol);
}

int socket_bind(int sock, unsigned short int port) 
{
    printf("bind to port %d\n", port);
    struct sockaddr_in sock_addr;
    bzero(&sock_addr, sizeof(struct sockaddr_in));
    sock_addr.sin_family = AF_INET;
    sock_addr.sin_addr.s_addr = htonl(INADDR_ANY);

    sock_addr.sin_port = htons(port);

    if(bind(sock, (struct sockaddr *) &sock_addr, sizeof(struct sockaddr)) == -1) 
    {
        printf("bind error %d\n", errno);
        return -1;
    }
    return 0;
}

int socket_listen(int sock)
{
    if (listen(sock, 50) == -1) 
    {
        printf("listen error %d\n", errno);
        return -1;
    }
    return 0;
}

void dump_fork(pid_t child_pid) 
{
	  pid_t parent = getppid();
    pid_t pid = getpid();
    printf("parent: %d, child: %d, pid: %d\n", parent, child_pid, pid);
}

int child(int argc, char** argv) 
{
	  printf("fork child process...\n");
    pid_t child_pid = fork();
    
    /*
    pid_t pid = getppid();
    pid_t process = getpid();
    printf("pid: %d, child: %d, process: \n", pid, child, process);
    */
    //*
    if (child_pid == 0) 
    {
    	  dump_fork(child_pid);
    } 
    else if (child_pid == -1)
    {
        dump_fork(child_pid);
    }
    else 
    {
        dump_fork(child_pid);
    }
    //*/
    return child_pid;
}

int start_acceptor_process(int argc, char** argv)
{
    return child(argc, argv);
}

void start_worker_process(int argc, char** argv, int *index, p_worker_t* w, int size)
{  
    pid_t child_pid = child(argc, argv);
    
    w[*index].pid = child_pid;
    w[*index].index = *index;
    
    //*
    if (child_pid == 0) 
    {
        dump_fork(child_pid);
    	  printf("worker process index: %d\n", *index);
    	  while (1) 
    	  {
    	      // loop to handle request...	
    	  }
    	  return;
    } 
    else if (child_pid == -1)
    {
        dump_fork(child_pid);
        printf(">worker process index: %d\n", *index);
        return;
    }
    else 
    {
        dump_fork(child_pid);
        printf(">>worker process index: %d\n", *index);
        if (*index < size) 
        {
        	  *index = *index + 1;
        	  start_worker_process(argc, argv, index, w, size);
        }
    }
    //*/
}

int main(int argc, char** argv) 
{
	  int child_pid = 0;
    int fd = -1;
    
    pid_t pid = getpid();
    pid_t parent = getppid();
    printf("pid: %d, parent: %d\n", pid, parent);
    
#ifdef USE_SOCK_NONBLOCK
    fd = _socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
#else
		fd = _socket(AF_INET, SOCK_STREAM, 0);
		if (fd == -1) 
		{
		    printf("socket error %d\n", errno);
    	  return 1;
		}
		else 
		{
		    printf("socket ok, socket: %d\n", fd);
		}

    socket_setnonblock(fd);
#endif

    if (socket_bind(fd, 2121) == -1)
    {
        return -1;
    }
    
    if (socket_listen(fd) == -1) 
    {
				return -1;
    }
    
    child_pid = start_acceptor_process(argc, argv);
    
    //*
    if (child_pid == 0) 
    {
        int i = 0;
    	  p_worker_t *w = (p_worker_t *) malloc(max_worker_process_num * sizeof(p_worker_t));
    	  
    	  
        dump_fork(child_pid);
        printf("acceptor process started...\n");
        
        start_worker_process(argc, argv, &i, w, max_worker_process_num);
    } 
    else if (child_pid == -1)
    {
        dump_fork(child_pid);
    }
    else 
    {
    		//*
    	  int new_fd = -1;
        struct sockaddr sock_addr;
    	  int addrlen = sizeof(struct sockaddr);
    	  //*/
    	  
    	  
    	  
        dump_fork(child_pid);
        
        
        //*
        printf("accepting connection...\n");
        while (1) 
        {  
        	  //printf("server socket: %d\n", fd);
            new_fd = accept(fd, &sock_addr, &addrlen);
            if (new_fd == -1) 
            {
            	  if (errno == EWOULDBLOCK) 
            	  {
            	      
            	  }
            	  else 
            	  {
                    printf("accept error %d\n", errno);
              	}
                continue;
            }
            else 
            {
                printf("accept new connection from %d\n", new_fd);
            }
      	}
      	//*/
    }
    //*/
    
    printf("started...\n");
}

?

論壇首頁 編程語言技術版

跳轉論壇:
Global site tag (gtag.js) - Google Analytics 开心农场种蔬菜赚钱 宁夏11选五平台哪个好 白小姐计划 山东群英会时间表 配资公司资金安全性 江苏11选五前三组遗漏 高手网彩票资料大金 秒速赛车 贵州快三号码推荐计划 3d图谜总汇全牛彩 3月27上证指数 北京快三大小单双 山西11选5玩法规则 贵州快三开奖结果等 2013年长线股票推荐 吉林快三预测大小单双 时时彩平台总代