zoukankan      html  css  js  c++  java
  • Linux父子进程的简单同步

    int fork()

    • 功能:创建一个子进程
    • 返回值:0-创建成功,-1-创建进程失败,>0-创建进程成功,返回返回子进程id

    int wait(int * status)

    • 功能:将调用的进程挂起,等待子进程运行结束
    • 参数:指向整数的指针,0-子进程正常结束,非0-出现运行有误
    • 返回值:调用正常-子进程id,调用进程无子进程-调用失败,返回-1

    int exit()

    • 功能:终止进程的执行
    • 返回值:无

    sleep(n)

    • 功能:进程随眠1秒
    • 参数:n-随眠时间

    实例代码

    1.1 父进程创建子进程,分别循环输出"I am parent."和"I am child."5次,每次输出一次后使用sleep(1)延时1s。

    #include<stdio.h>
    #include<unistd.h>
    /*
    1_1.c
    父进程创建子进程,分别循环输出
    "I am child."和"I am parent."
    每输出一次随眠1s。
    */
    main()
    {
    	int p;
    	while((p=fork())==-1);
    	if(p==0)
    	{/*子进程块*/
    		int i;
    		for(i=0;i<5;i++)
    		{
      			printf("I am child.\n");
      			sleep(1);
    		}
    	}
    	else
    	{/*父进程块*/
    		int i;
    		for(i=0;i<5;i++)
    		{
      			printf("I am parent.\n");
      			sleep(1);
    		}
    	}
    }
    

    1.2 在1.1的基础上利用exit()和wait()实现父子进程间的同步。

    #include<stdio.h>
    #include<unistd.h>
    #include<stdlib.h>
    /*
    简单的进程同步:
    父进程等待子进程输出后再输出
    */
    main()
    {
    	int p;
    	while((p=fork())==-1);
    	if(p==0)
    	{/*子进程块*/
    	 	int i;
    		for(i=0;i<5;i++)
    		{
    		   	printf("I am child.\n");
      			sleep(1);
    		}
    		exit(0);
    	}
    	else
    	{/*父进程块*/
    	  	int i;
    		for(i=0;i<5;i++)
    		{
    	  		wait(0);
    	  		printf("I am parent.\n");
    	  		sleep(1);
    		}
    	}
    }
    

    扩展链接

    fork系统调用

  • 相关阅读:
    常见的四种文本自动分词详解及IK Analyze的代码实现
    用java语言通过POI实现word文档的按标题提取
    spark的运行模式
    团队冲刺日志2
    简单之美-软件开发实践者的思考 03
    简单之美-软件开发实践者的思考 02
    简单之美-软件开发实践者的思考 01
    学习进度 15
    构建之法 06
    构建之法 05
  • 原文地址:https://www.cnblogs.com/goodswarm/p/9932198.html
Copyright © 2011-2022 走看看