linux process fork related

to demonstrate the underlying principle of the unix api fork and fork-related contents(wait waitpid) etc, i wrote these two pieces of code as following , both of which repersented my personal understanding the fork.
i strongly reconmend you to read the linux source code concerning with fork if you really want to grasp the these knowlegement and application of them , if so, it will be definitely inducive for our practice projects.
So here is the deal:



No 1 : process_fork.c

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

main()
{

    pid_t pid, status;
   
    printf("parent id is %d/n",getpid());
   
    if((pid=fork())==0){
        sleep(1);
        printf("child id is %d/n",getpid());
       
        return;
    }
   

    if((pid=fork())==0){

        sleep(2);
        printf("child id is %d/n",getpid());
       
        return;
    }
   

    if((pid=fork())==0){

        sleep(3);
        printf("child id is %d/n",getpid());
       
        return;
    }
   
    //here, if u want to reclaim the spicific process according to its pid, just use waitpid()        
    pid = wait(&status);
    if(pid>0)       
        printf("%d reclaimed/n",pid);
   
    sleep(4);//enable the parent to wait until the termination of all its children
}




No 2 : line_buffer.c
#include <stdio.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>

main ()

{

        pid_t pid,status;

        printf("fork!/n");    // totally different circumstance u will find when u place printf("fork!") or printf("fork!/n")

        pid=fork();

        if (pid < 0)

                printf("error in fork!/n");

        else if (pid == 0){
            printf("i am the child process, my process id is %d/n",getpid());


            sleep(5);
            exit(5);




        }

        else{
            printf("i am the parent process, my process id is %d/n",getpid());
           
            pid = wait(&status);

            if ( WIFEXITED(status) )   /* 如果WIFEXITED返回非零值 */
            {
                printf("The child process %d exit normally./n", pid);
                printf("the return code is %d./n", WEXITSTATUS(status));
            }
        }

           
        exit(0);
}



there's inevitablely some bugs or mistakes, if so , really sorry about that !
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值