一 、 进程的创建
1.fork();创建一个独立的进程
pid_t fork(void);
使用这个命令会创建一个独立于父进程而且拷贝父进程全部存储空间的子进程
返回值有三种情况
1.父进程会返回子进程的进程号,pid>0
2.子进程会返回0;pid = 0 ;
3.出错会返回-1 ; pid = -1;
使用模板:
if(pid > 0)
{
//父进程要执行的语句
}
else if(pid == 0)
{
//子进程的语句
}
else
{
//出错的语句。
}
获得本进程的pid getpid();
获得父进程的pid getppid();
如果父进程结束了而子进程并没有结束,子进程就会变成孤儿进程,最后由inti()回收
如果子进程技术而父进程没有结束,子进程将会变成僵尸进程,必须由父进程主动回收。
父进程回收子进程,使用函数wait(),父进程会等待子进程接受才会继续执行
如果父进程不想主动释放子进程可以使用一级缓冲
A -- > fork -- -- wait
B -- fork -- //子进程在在建立一个进程,让真正程序为孤儿进程,使用init来回收
C -- end
2.使用exec函数族
int execl(const char *path, const char *arg, ...);
int execlp(const char *file, const char *arg, ...);
int execle(const char *path, const char *arg,
..., char * const envp[]);
int execv(const char *path, char *const argv[]);
int execvp(const char *file, char *const argv[]);
int execvpe(const char *file, char *const argv[],
char *const envp[]);
函数返回:只有错误的时候才会返回-1,如果函数正确进程将会被替换。
创建的子进程将会替代父进程,占用父进程的pid。
execl(),中第一参数是想要执行程序的路径,下面的是要执行程序的参数,结尾应为NULL ls -a -l,有三个参数
execlp(),从环境变量中找文件执行,其他的为可变参数,结束为NULL
execle(),从一个环境变量数组中寻找程序执行,必须传入一个环境变量的数组
下面的三个是传入字符串数组,而不是一个一个单独的字符串。
例题:1.父子进程一个向文件中写数据,一个计算文件的大小
2.调用系统提供的程序,仿写终端。
#include <stdio.h> #include <unistd.h> #include <string.h> #include <stdlib.h> int readFromSTDIN(char * p,int count); //从标准输入获取字符串。 void split2(char *s,char d,char *r[5]); //分割字符串。 int main() { //定义一个数组,用来存储参数 //参数的个数是不确定的,如何获取不一样的 //从标准输入调用系统函数获取字符串,获取包括换行和空格。 //使用strchr和strncpy,分割字符 char caCmd[256] ={'