Linux 进程控制

fork 函数生成子进程

#include 
#include 

int main() {
    int pid;
    pid = fork(); // 创建一个子进程
    if (pid < 0) {
        printf("fork failed\n");
        return 0;
    }
    if (pid == 0) {
        printf("child process pid: %d\n", pid);
        printf("It's child, pid is %d\n", getpid());
    } else {
        printf("parent process pid: %d\n", pid);
        printf("It's parent, pid is %d\n", getpid());
    }
}

输出

parent process pid: 6437
It's parent, pid is 6436
child process pid: 0
It's child, pid is 6437

Process finished with exit code 0

创建成功。

  • 父进程返回子进程的 pid=6437,子进程返回的pid=0。
  • 父进程pid=6436,子进程pid=6437。

注意,上面的程序 pid是fork函数的返回值,而 getpid函数返回的才是当前进程的pid

UNIX系统在实现 fork() 调用完成的主要工作

  1. 为子进程在进程表中分配一个空闲的proc结构
  2. 赋给子进程一个唯一的进程标识符pid
  3. 复制一个父进程上下文的逻辑副本
  4. 增加与父进程相关联的文件表和索引节点表的引用次数
  5. 创建成功对父进程返回子进程的pid.对子进程返回0.创建不成功返回-1

wait 函数

  • wait() 会暂时停止目前进程的执行,直到有信号来到或子进程结束
  • 如果在调用 wait() 时子进程已经结束,则 wait()会立即返回子进程结束状态值。子进程的结束状态值会由参数 status 返回, 而子进程的进程识别码也会一起返回。如果不在意结束状态值,则参数status 可以设成 NULL。
  • 父进程 fork 派生1个子进程后,常常需要 等待子进程执行完 才能继续执行。
#include 
#include 
#include 

int main() {
    int pid, tmp;
    int status;
    printf("当前进程pid: %d\n", getpid());
    pid = fork();
    if (pid < 0) {
        printf("call fork() failed\n");
    }
    if (pid == 0) {
        printf("child process %d finished\n", getpid());
        exit(1);
    } else {
        tmp = wait(&status); // 父进程等待子进程完成
        printf("the tmp pid is %d\n", tmp);
        printf("the pid is %d\n", pid); // 父进程的返回值
        if (tmp != pid) {
            printf("call wait() failed\n");
        } else {
            printf("parent process %d finished\n", getpid());
        }
    }
}

输出

当前进程pid: 7378
child process 7379 finished
the tmp pid is 7379
the pid is 7379
parent process 7378 finished

Process finished with exit code 0

你可能感兴趣的:(Linux 进程控制)