进程控制可以分为进程创建、终止,获取进程的信息
创建进程可以使用如下函数
system()
、fork()
、vfork()
和popen()
函数
#include <stdio.h>
#include <stdlib.h>
int main()
{
system("ps -o pid,ppid,comm "); //调用system函数
return 0;
}
system函数内部通过调用fork()
函数、exec()
函数,以及waitpid()
函数来实现的
下面是system()
函数的源代码
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <unistd.h>
int system(const char * cmdstring)
{
pid_t pid;
int status;
if(cmdstring == NULL) //如果命令为NULL,直接返回
{
reutrn (1);
}
if((pid = fork())<0) //调用fork()函数,创建新进程
{
status = -1;
}
else if(pid == 0) //子进程
{
//调用execl()函数来启动新的程序
execl("/bin/sh", "sh", "-c", cmdstring, (char \*)0);
_exit(127);
}
else //父进程
{
while(waitpid(pid, &status, 0) < 0) //等待子进程结束
{
if(errno != EINTER)
{
status =-1;
break;
}
}
}
return status;
}