zoukankan      html  css  js  c++  java
  • 2.1 进程控制之fork创建子进程

    fork()函数


    目标:熟悉fork创建一个和多个子进程子线程

    函数原型:pid_t fork(void); 

    返回值:成功返回:① 父进程返回子进程的ID(非负) ②子进程返回 0 ;

        失败返回-1

    注意:pid_t类型表示进程ID,它是有符号整型。

    例程一:创建一个子线程

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 #include <unistd.h>
     4 int main(void)
     5 {
     6   pid_t pid;
     7   pid = fork();//创建子进程
     8   //调用出错
     9   if(pid == -1){
    10     printf("fork failed
    ");
    11     return 1;
    12   }
    13   else if(pid){ //返回值大于0,为父进程
    14     printf("The father return value is %d
    ",pid);
    15     printf("The father pid is %d
    ",getpid());
    16     printf("The father ppid is %d
    ",getppid());
    17     sleep(2);
    18   }
    19   else{    //返回值等于0,为子进程
    20     printf("The child return value is %d
    ",pid);
    21     printf("The child pid is %d
    ",getpid());
    22     printf("The child ppid is %d
    ",getppid());
    23  }
    24  return 0;
    25 }

    编译执行结果:

    例程二:循环创建多个子线程

     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 #include <unistd.h>
     4 
     5 int main(void)
     6 {
     7     int i;
     8     pid_t pid;
     9     for (i = 0; i < 5; i++) {
    10         pid = fork();
    11         if (pid == 0) {  //若为子进程则直接break退出
    12             break;
    13         }
    14     }
    15 
    16     if (i < 5) {  //子进程部分 
    18         sleep(i);
    19         printf("I'am %d child , pid = %u
    ", i+1, getpid());
    20 
    21     } else  {     //父进程
    22         sleep(i);
    23         printf("I'm parent
    ");
    24     }
    25     return 0;
    26 }

    编译执行结果:

    其中,getpid()函数: 获取当前进程ID,原型为pid_t getpid(void);

       getppid()函数:获取当前进程的父进程ID,原型为pid_t getppid(void);

  • 相关阅读:
    Orderly Class
    POJ2513 【并查集+欧拉路径+trie树】
    POJ2195 Going Home【KM最小匹配】
    洛谷P2604 最大流+最小费用最大流
    小数转分数
    威尔逊定理
    luogu P6564 [POI2007] 堆积木KLO 树状数组+dp
    Codeforces Round #644 (Div. 3) H——Binary Median 二分
    luogu P4933 大师 线性dp
    Codeforces Round #643 (Div. 2) D——Game With Array
  • 原文地址:https://www.cnblogs.com/lxl-lennie/p/10212732.html
Copyright © 2011-2022 走看看