用fork()函数产生“进程栈”或者“链式进程”代码,可运行

 

/***********************************************
*产生5个子进程
*(1)5个子进程栈
*(2)5个链式子进程
***********************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <wait.h>
/***************************************************************
函数名称:fork_by_father
函数功能:创建num个子进程栈
输入参数:(int)num:子进程数量
输出参数:无
***************************************************************/
void fork_by_father(int num)
{
    pid_t pid;
    int i;
    //创建num个子进程,只能由父进程创建
    for (i=0; i<num; i++)
    {
        pid = fork();
        //为子进程或者子进程创建失败均退出
        if (pid==0 || pid<0)
        {
            break;
        }
    }
    //fork失败
    if (pid < 0)
    {
        perror("fork");
        exit(1);
    }
    //子进程
    else if (pid == 0)
    {
        printf("子进程%d PID = %d,对应父进程 PID = %d\n", i+1, getpid(), getppid());
        exit(0);
    }
    //父进程
    else if (pid > 0)
    {
        printf("父进程  PID = %d\n", getpid());
        getchar();
        exit(0);
    }
}
/***************************************************************
函数名称:fork_by_child
函数功能:创建num个链式子进程
输入参数:(int)num:子进程数量
输出参数:无
***************************************************************/
void fork_by_child(int num)
{
    pid_t pid;
    int i;
    //创建num个链式进程,只能由子进程创建
    for (i=0; i<num; i++)
    {
        pid = fork();
        //为父进程或者子进程创建失败均退出
        if (pid>0 || pid<0)  
        {
            break;
        }
    }
    //fork失败
    if (pid < 0)
    {
        perror("fork");
        exit(1);
    }
    //fork成功
    else if (pid >= 0)
    {
        if (i == 0)
        {
            printf("父进程  PID = %d\n",getpid());
        }
        else
        {
            printf("子进程%d PID = %d,对应父进程 PID = %d\n", i, getpid(), getppid());
        }
        getchar();
        exit(0);
    }
}
/**************************************
*主函数
*(1)加参数father,产生5个子进程栈
*(2)加参数child, 产生5个链式子进程
**************************************/
int main(int argc, char *argv[])
{
    if (strcmp(argv[1], "father") == 0)
    {
        fork_by_father(5);
    }
    else if (strcmp(argv[1], "child") == 0)
    {
        fork_by_child(5);
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值