unix标准把进程定义为:“一个其中运行着一个或多个线程的地址空间和这些线程所需要的系统资源”。进程直接可以共享程序代码,但不能对用来存放程序代码的内存进行写操作,即程序代码是以只读的方式加载到内存的。同时系统函数库也可以被共享。除了一些共享资源外,进程有自己的栈空间,用于保存局部变量和控制函数的调用与返回。进程还有自己的环境空间。
1.查看进程
使用 ps -ef命令
2. 启动新进程
a.利用system函数在一个程序内部启动另一个程序
#include <stdlib.h>
int system(const char* string)
运行以字符串形式传递给它的命令。如system("ps ax");
b.利用exec系列函数把当前进程替换为另外一个新进程。各个函数名称如下
execl(char* path,const char* arg0,……)
execlp(char* file,const char* arg0,……)
execle(char* path,const char* arg0,……,char* const envp[])
execv(char* path,const char* arg[])
execvp(char* file,const char* arg[])
execve(char* path,const char* arg[],char* const envp[])
例子:exelp("ps","ps","ax")
c.复制进程映像
#include <sys/types.h>
#include <unistd.h>
pid_t fork(void);
通过fork创建一个新进程,新进程几乎和原进程一模一样,代码相同,但有自己的数据空间和环境空间。fork子进程返回的是0,父进程返回值大于0.
3.等待进程
#include <sys/types.h>
#include <sys/wait.h>
pid_t wait(int* stat_loc);
wait系统调用将暂停父进程直到它的子进程结束为止。这个调用返回子进程的pid。如果stat_loc不是空指针,状态信息将被写入它所指向的位置。
另外一个等待进程的函数是waitpid
pid_t waitpid(pid_t pid, int* stat_loc,int options)
options最有用的一个选项是WNOHANG,它的作用是防止waitpid调用将调用者的执行挂起。