@Linux系統程序
程序相關解釋
程序:運作起來的程式在記憶體中的鏡像
程序号:系統配置設定給程序的一個編号,用于标記該程序, 便于系統排程管理 該程序。程序号唯一,程序号也是有限。程序結束後,會将程序号歸還系統。系統可以将歸還的程序号配置設定給新的程序。
程序控制塊(pcb):一塊記憶體空間,存放程序的相關資訊,便于系統管理。程序号,打開的檔案清單,信号清單…
并發:宏觀上,多個程式同時運作;微觀上,某個時刻,隻有一個程式在運作
程序排程算法:先來先執行,短作業優先原則,時間片輪轉,優先級排程,多優先級隊列時間片輪轉
fock()函數建立程序
#include <sys/types.h>
#include <unistd.h>
pid_t fork(void);
fork()通過複制調用程序來建立一個新程序。新進流程被稱為子程序。原程序被稱為父程序。
子程序和父程序在不同的記憶體空間中運作。在fork()時,兩個記憶體空間具有相同的内容。 其中一個過程不會影響另一個程序。
成功後,子程序的程序号将在父程序中傳回,并且在子程序中傳回0。失敗時,在父級中傳回-1,沒有建立子程序。
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
int main(void)
{
int i = 0;
char caMsg[128] = {'\0'};
pid_t pid = -1;
pid = fork();
if (pid > 0) //parent
{
i = 3;
printf("parent msg addr = 0x%p\n", caMsg);
strcpy(caMsg, "this is parent...");
}
else if (0 == pid) //child
{
i = 6;
printf("child msg addr = 0x%p\n", caMsg);
strcpy(caMsg, "this is child...");
}
else if (-1 == pid)
{
perror("fork");
exit(EXIT_FAILURE);
}
for (; i>0; i--)
{
printf("%s\n", caMsg);
sleep(1);
}
return 0;
}
雖然在Linux中運作顯示父程序與子程序位址一樣,但其并不相同。
猜猜有幾個程序
1.列印多少個g?
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main(void)
{
for(int i=0;i<2;i++)
{
fork();
printf("g\n");
}
return 0;
}
2.列印多少個g?
int main(void)
{
//總共有多少個程序
int i = 0;
for (; i<2; i++)
{
fork();
printf("g");
}
return 0;
}
答案:1、6個 2、8個