pcntl_fork 创建了一个子进程,这个时候就会存在父进程和子进程,cpu先调度哪个进程?

pcntl 封装了可以控制进程优先级的函数 pcntl_setprioritysetpriority),修改任意进程的优先级,pcntl_getprioritygetpriority)获取任意进程的优先级。

进程的观察命令:top

top - 23:28:59 up 13:13,  1 user,  load average: 0.30, 1.20, 1.61
任务: 386 total,   1 running, 385 sleeping,   0 stopped,   0 zombie
%Cpu(s):  2.8 us,  1.7 sy,  0.1 ni, 95.3 id,  0.0 wa,  0.0 hi,  0.2 si,  0.0 st
MiB Mem :   5855.6 total,    664.6 free,   3875.4 used,   1315.7 buff/cache
MiB Swap:    976.0 total,    364.7 free,    611.3 used.   1379.6 avail Mem 

进程号 USER      PR  NI    VIRT    RES    SHR    %CPU  %MEM     TIME+ COMMAND                                                                        
7305  wanger    20   0  4956504   454380 52432 S  4.6   7.6  28:24.62 gnome-shell

...

在 Linux 系统中,一般把进程/线程称为任务Task。

  • PR priority 进程的优先级

  • NI nice 进程的nice值 nice值越小,则优先级越高

进程的nice越小,则进程的PR优先级越高,cpu就先运行这个进程。

示例:

<?php

$nice = $argv[1];
$start = time();
$count = 0;

$pid = pcntl_fork();

if ($pid == 0){

    fprintf(STDOUT, "child process pid=%d,nice=%d\n", posix_getpid(), pcntl_getpriority());

    pcntl_setpriority($nice, getmypid(), PRIO_PROCESS);

    fprintf(STDOUT, "child process pid=%d,nice=%d\n", posix_getpid(), pcntl_getpriority());

    while (1){

        $count++;

        if (time() - $start > 5){
            break;
        }

    }

}else{

    fprintf(STDOUT, "parent process pid=%d,nice=%d\n", posix_getpid(), pcntl_getpriority());

    // pcntl_setpriority($nice, getmypid(), PRIO_PROCESS);

    fprintf(STDOUT, "parent process pid=%d,nice=%d\n", posix_getpid(), pcntl_getpriority());

    while (1){

        $count++;

        if (time() - $start > 5){
            break;
        }

    }

}

fprintf(STDOUT, "pid=%d,nice=%d,count=%d\n", posix_getpid(), pcntl_getpriority(), $count);