进程及进程管理

#include<stdio.h>
#include<sys/types.h>
#include<sys/wait.h>
#include<unistd.h>
#include<stdlib.h>
#include<fcntl.h>
//#include<sys/exits.h>

int global = 22;
char buf[] = "the test content!/n";
void exit_check(int stat)    //waitpid的作用是等待子进程退出并回收资源,同时通过WIFEXITED等宏调用可以检测子进程退出状态。
{
 if(WIFEXITED(stat))
 {
  printf("exit abnormally!the signal code is:%d/n",WEXITSTATUS(stat));
 }
 else if(WIFSIGNALED(stat))
 {
  printf("exit abnormally!the signal code is:%d/n",WTERMSIG(stat));
 }
}

int main()
{
 int test = 0,stat;
 pid_t pid;
 if(write(STDOUT_FILENO,buf,sizeof(buf))!=sizeof(buf))    //相当于printf
 {
  perror("write error!");
 }
 printf("fork test!/n");
 
 pid = vfork();
 if(pid == -1)
 {
  perror("fork");
  exit(0);
 }
 else if(pid == 0)
 {
  global++;
  test++;
  printf("global=%d test=%d Child,my PID is %d/n",global,test,getpid());
  if(execl("/bin/ps","ps","-au",NULL)<0)    //使用execv函数族
   perror("execl error!");
  printf("this message will never be printed!/n");
  exit(0);
 }
 if(waitpid(pid,&stat,0)==pid)
 {
  exit_check(stat);
 }
 global += 2;
 test += 2;
 printf("global = %d test = %d Parent,my PID is %d/n",global,test,getpid());
 exit(0);
}

 

waitpid()使用实例:

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

int main()
{
 pid_t pc,pr;
 pc = fork();
 if(pc < 0)
 {
  printf("Error fork/n");
 }
 else if(pc == 0)     //子进程
 {
  sleep(5);    //子进程暂停5秒
  exit(0);    //子进程正常退出
 }
 else
 {
  do           //循环测试子进程是否退出
  {
   pr = waitpid(pc,NULL,WNOHANG);
   if(pr == 0)          {          //若子进程还未退出,则父进程不阻塞
    printf("The child process has not exited/n");
    sleep(1);
   }
  }while(pr == 0);
  if(pr == pc){          //若发现子进程退出,打印相应情况
   printf("Get child exit code: %d/n",pr);
  }
  else
  {
   printf("Some error occured./n");
  }
 }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值