shell 和進程


shell和進程的關系:

我們從login shell 說起,login shell用於表示登陸進程,是指用戶剛登錄系統時,由系統創建,用以運行shell 的進程。

這里先運行幾個命令:

打印登陸進程(一直存在的,直到登陸退出)ID

george.guo@ls:~$ echo $PPID
3411
george.guo@ls:~$ ps -aux | grep 3411
george.+ 3411 0.0 0.0 99004 4520 ? S 11:00 0:00 sshd: george.guo@pts/46
打印登陸進程fork出的shell進程(一直存在的,直到登陸退出)
george.guo@ls:~$ echo $$
3412
george.guo@ls:~$ ps -aux | grep 3412
george.+ 3412 0.5 0.0 21380 5120 pts/46 Ss 11:00 0:00 -bash

從上面的幾個命令可以看出:

登陸進程ID是3411,它創建了bash shell子進程3412。以后的腳本執行,

3412我們這里稱為主shell,它會啟動子shell進程處理腳本。

(注:在bash中,子shell進程的PID存儲在一個特殊的變量‘$$’中,PPID存儲子shell父進程的ID。)

 

我們寫兩個小程序驗證下:

george.guo@ls:~$ cat yes.c 

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
        pid_t pid;
        pid_t ppid;

        pid = getpid();
        ppid = getppid();
        system("./test");       //system will fork a process for exec ./test
        printf("yes pid = %d, yes ppid =  %d\n", pid, ppid);
}

george.guo@ls:~$ cat test

#!/bin/bash
echo "PID of this script: $$"
echo "test's PPID(system's fork id) = $PPID"
echo "tests's pid = $$"

運行結果如下:

george.guo@ls~$ ./yes

PID of this script: 6082
tests PPID(system's fork id)= 6081
echo tests self pid is 6082
yes PID = 6080, yes PPID = 3412

可見yes進程的父進程ID是3412,即登陸進程fork的bash shell子進程,主shell。這是因為

yes是由主shell執行的。yes進程ID是6080,調用system, fork出子shell ID為6081。

對於system調用:

使用system()運行命令需要創建至少兩個進程。一個用於運行shell (這里其ID為6081),

另外一個或多個則用於shell 所執行的命令(這里是一個子shell,就是腳本test本身).

腳本test本身進程ID為6082。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM