shell 和進程,shell進程

來源:互聯網
上載者:User

shell 和進程,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/bashecho "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。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.