Chinaunix首页 | 论坛 | 博客
  • 博客访问: 36340
  • 博文数量: 25
  • 博客积分: 0
  • 博客等级: 民兵
  • 技术积分: 258
  • 用 户 组: 普通用户
  • 注册时间: 2014-02-08 15:12
文章分类

全部博文(25)

文章存档

2015年(2)

2014年(23)

我的朋友

分类: LINUX

2014-04-09 22:19:29

进程控制可以分为进程创建、终止,获取进程的信息
创建进程可以使用如下函数
system()、fork()、vfork()和popen()函数

点击(此处)折叠或打开

  1. #include <stdio.h>
  2. #include <stdlib.h>

  3. int main()
  4. {
  5.   system("ps -o pid,ppid,comm "); //调用system函数
  6.    return 0;
  7. }
system函数内部通过调用fork()函数、exec()函数,以及waitpid()函数来实现的
下面是system()函数的源代码

点击(此处)折叠或打开

  1.   1 #include <sys/types.h>
  2.   2 #include <sys/wait.h>
  3.   3 #include <errno.h>
  4.   4 #include <unistd.h>
  5.   5
  6.   6 int system(const char * cmdstring)
  7.   7 {
  8.   8     pid_t pid;
  9.   9     int status;
  10.  10     if(cmdstring == NULL) //如果命令为NULL,直接返回
  11.  11     {
  12.  12         reutrn (1);
  13.  13     }
  14.  14     if((pid = fork())<0) //调用fork()函数,创建新进程
  15.  15     {
  16.  16         status = -1;
  17.  17     }
  18.  18     else if(pid == 0) //子进程
  19.  19     {
  20.  20         //调用execl()函数来启动新的程序
  21.  21         execl("/bin/sh", "sh", "-c", cmdstring, (char *)0);
  22.  22
  23.  23         _exit(127);
  24.  24     }
  25.  25     else //父进程
  26.  26     {
  27.  27         while(waitpid(pid, &status, 0) < 0) //等待子进程结束
  28.  28         {
  29.  29             if(errno != EINTER)
  30.  30             {
  31.  31                 status =-1;
  32.  32                 break;
  33.  33             }
  34.  34         }
  35.  35     }
  36.  36     return status;
  37.  37 }


阅读(807) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~