建立進程(Process)
在Linux中,創造新進程的方法只有一個,就是函式fork()。其他一些函式,如system(),看起來似乎也能創建新的進程,如果看一下它們的來源碼(source code)就會明白,它們實際上也在內部呼叫了fork。包括我們在命令行下運行應用程式,新的進程也是由shell呼叫函式fork製造出來的。
fork
fork是UNIX一個系統呼叫(system call),process fork時,會複製一個跟自己完全一模一樣的process (with differentpid),並利用系統呼叫完成之傳回值,來區分parentprocess 與child process,而分別賦予child process不同的功能。
fork (.c)
- “fork”的意思就是一分為二,把當前進程複製出一個新的進程。當前的進程就是新進程的父進程,新進程稱為子進程。
- fork把子進程ID傳回給父進程,把0傳回給子進程,通過對傳回值的檢查就可知道當前是父進程還是子進程。
首先建立一個檔案 fork_exam.c,輸入以下程式碼
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
pid_t pid;
if ((pid = fork()) > 0)
printf("I am the parent, my pid = %u, my child is pid = %u\n", getpid(), pid);
else if (pid == 0)
printf("I am the child, my pid = %u, my parent is pid = %u\n", getpid(), getppid());
else
{
perror("fork");
return 1;
}
return 0;
}
接著編譯這個檔案並且執行他
gcc -o fork_exam fork_exam.c
./fork_exam
再來將程式碼更改成以下,使用視覺化的方式查看進程
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
int main(void)
{
pid_t pid;
if ((pid = fork()) > 0){
printf("I am the parent, my pid = %u, my child is pid = %u\n", getpid(), pid);
for (int i=0; i<1000; i++) {
printf("*");
fflush(stdout);
sleep(1);
}
}
else if (pid == 0){
printf("I am the child, my pid = %u, my parent is pid = %u\n", getpid(), getppid());
for (int i=0; i<1000; i++) {
printf("a");
fflush(stdout);
sleep(1);
}
}
else
{
perror("fork");
return 1;
}
return 0;
}
重新編譯一次,再次執行程式
強制中斷進程
輸入以下的指令可以查看目前運行的所有進程
ps -u
找到想要中斷的進程 pid,使用以下的指令殺掉
kill -9 PID
Latest posts by SHXJ (see all)
- 受保護的內容: NAS 版 Mathbot 管理網站與 Linebot 啟動方法 - 2024 年 11 月 15 日
- Realtime 啥鬼的 - 2021 年 6 月 15 日
- nodejs 數學遊戲 - 2021 年 6 月 8 日



