本文主要内容为Linux系统下进程的产生方式


1.学习进程的产生方式之前首先要明白进程号的概念

    每个进程在初始化的时候,系统都分配了一个ID号,用于表示该进程,进程号的获取方法为调用函数getpid()或getppid()

1.1getpid()  返回当前进程的ID号

#include<stdio.h>
#include<unistd>
pid_t getpid(void);
1.2.getppid()返回当前进程的父进程的ID号
         #include<stdio.h>
#include<unistd>
                pid_t getppid(void);
        1.3.getpid()和getppid()函数的使用方法
                #include<stdio.h>
                #include<sys/types.h>
                #include<unistd.h>
                int main(){
                    pid_t pid,ppid;
                    printf("当前进程ID号为:%d\n",getpid());
                    printf("当前进程的父进程ID号为:%d\n",getppid());
                    return 0;
 
进程的产生的方式有:进程复制fork(),system()方式,exec()函数系列 ,本文主要讲,fork()、和system()两只方式。exec()函数系列将放在其他文章中讲解。              }


2.进程复制fork():

    fork函数以父进程为蓝本复制一个进程,ID号和父进程的ID号不同。只有内存等与父进程不同,其他与进程共享,只有在父进程或子进程进行了修改后,才重生一份

2.1.fork()函数

#include<sys/types.h>
#include<unistd.h>
pid_t fork(void);
            特别注意:fork()执行一次返回两次,父进程中返回的是子进程的id号,而子进程中返回的是0
2.2.fork()函数的例子
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>

int main(void){
pid_t pid;

pid = fork();

if(pid == -1){
printf("子进程产生错误");
return -1;
}else if(pid == 0){
printf("子进程,fork返回值:%d,ID:%d,父进程:ID%d\n",pid,getpid(),getppid());
return 0;
}else{
printf("父进程,fork返回值:%d,ID:%d,父进程ID:%d\n",pid,getpid(),getppid());
}
return 0;
}
 本人机子上的执行结果:
        ]# ./fork.o 
            父进程,fork返回值:2894,ID:2893,父进程ID:2778
            子进程,fork返回值:0,ID:2894,父进程:ID1
从执行的结果看以看出,父进程的返回值和子进程的ID正好相等。

3 system()函数的方式
    3.1.system()函数介绍
system()是调用shell中的外部命令,在当前进程中开始另外一个进。
调用system()函数时,会调用fork()、execve()、waitpid()等函数,其中任意个失败,将导致system()函数调用失败
函数原型:
     #include<stdlibh>
     #include<const char *command>
*当调用失败返回-1;
*当sh不能执行时,返回127
*调用成功返回进程状态值
    3.2 system()函数的执行的例子
            #include<stdio.h>
            #include<unistd.h>
            #include<stdlib.h>
            int main(){
                int ret;
                
                printf("当前进程ID号为:%d\n",getpid());
                ret = system("ping www.baidu.com -c 2");                //system()函调用
的时是/bin/sh—c command
                printf("返回的值为:%d\n",ret);

            return 0;
            }

https://blog.51cto.com/wewin11235/1620509