进程的fork、wait、exec

  • fork

C语言用fork()创建一个子进程时,子进程会复制父进程,子进程会从fork()函数的调用出返回。子进程对于fork()函数的返回值是0,父进程返回值是子进程的PID,如果创建子进程失败,fork()返回值小于0。
子进程不一定会比父进程执行的慢,当父进程创建子进程时,子进程会和父进程抢占CPU的资源。

下面父进程执行200次循环,子进程执行20次循环,少于父进程执行的循环次数,所以一般子进程会比父进程执行的快一些。

#include  <stdio.h>
#include  <sys/types.h>
#define   MAX_COUNT  200
void  ChildProcess(void);                /* child process prototype  */
void  ParentProcess(void);               /* parent process prototype */
void  main(void)
{
     pid_t  pid;
     pid = fork();
     if (pid < 0)
     	printf("fork failed");
     else if (pid == 0) 
          ChildProcess();
     else 
          ParentProcess();
}
void  ChildProcess(void)
{
     int   i;
     for (i = 1; i <= 20; i++)
          printf("   This line is from child, value = %d\n", i);
     printf("   *** Child process is done ***\n");
}
void  ParentProcess(void)
{
     int   i;
     for (i = 1; i <= MAX_COUNT; i++)
          printf("This line is from parent, value = %d\n", i);
     printf("*** Parent is done ***\n");
}

*wait

调用wait,父进程会等待子进程完成后再执行。wait的返回值是父进程等待的子进程的PID。

#include  <stdio.h>
#include  <sys/types.h>
#define   MAX_COUNT  200
void  ChildProcess(void);                /* child process prototype  */
void  ParentProcess(void);               /* parent process prototype */
void  main(void)
{
     pid_t  pid;
     pid = fork();
     if (pid < 0)
     	printf("fork failed");
     else if (pid == 0) 
          ChildProcess();
     else {
     
          ParentProcess();
}
void  ChildProcess(void)
{
     int   i;
     for (i = 1; i <= 20; i++)
          printf("   This line is from child, value = %d\n", i);
     printf("   *** Child process is done ***\n");
}
void  ParentProcess(void)
{
     int   i;
     for (i = 1; i <= MAX_COUNT; i++)
          printf("This line is from parent, value = %d\n", i);
     printf("*** Parent is done ***\n");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值