獲取ID
#include<sys/types.h>
#include<unsstd.h>
。pid_t getpid(void)
獲取本進程ID
。pid_t gettppid(void)
獲取父進程ID
eg:
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
int main (void)
{
printf("PID = %d\n", getpid());
printf("PPID = %d\n",getppid());
return 0;
}
#include<unistd.h>
pid_t fork(void)
功能:創建子進程
fork 的奇妙之處在於它被調用一次,卻返回兩次,有三種不同的返回值:
1、在父進程中,fork返回新創建的子進程的PID;
2、在子進程中,fork返回0;
3、如果出現錯誤,fork返回一個負值
創建進程-fork
eg:
#include<sys/types.h>
#include<unistd.h>
int main (void)
{
pid_t pid;
pid = fork();
if(pid<0)
printf("error in fork!%d\n",fork);
else if(pid==0)
printf("i am the child process,id=%d\n",getpid());
else
printf("i am the parent process,id is %d\n",getppid());
}
在pid=fork()之前,只有一個程序在執行,但在執行了這句話之後,就變成了兩個進程在執行了,這兩個進程共享代碼段,將要執行的嚇一跳語句都是if(pid==0).兩個進程中,原來就存在的那個進程就被稱爲父進程,出現新的那個被稱爲子進程,父子進程區別於進程標誌符(PID)不同。
eg:
#include<stdio.h>
#include(unistd.h)
int main(void)
{
pid_t pid;
int count=0;
pid = fork();
count++;
printf("count=%d\n",count);
return 0;
}
運行結果:count = 1
count = 1
子進程的數據空間、堆棧空間都會從父進程得到一個拷貝,而不是共享,在子進程中對count進行+1操作,並沒有影響父進程的count值,父進程的count值仍未0.
創建vfork
#include <sys/tppes.h>
#include<unistd.h>
pid_t vfork(void)
功能:創建子進程。
區別:
1、fork:子進程拷貝父進程的數據段。
vfork:子進程與父進程共享數據段
2、fork:父、子進程執行次序不確定
vfork:子進程先運行,父進程後運行
exec函數族
exec用被執行的程序替換調用它的程序。
區別:
fork創建一個新的進程,產生新的PID。
exec啓動一個新程序,替換原有的進程,因此進程PID不會改變。
#include<unistd.h>
int execl(const char *path,const char * arg1,...)
參數:
path:被執行程序名(含完整路徑)
arg1-argn:被執行程序所需的命令行參數,含程序名,以空指針NULL結束
eg:
#include<inistd.h>
int main(void)
{
execl("/bin/ls","ls","-al","/etc/passwd",(char *)0");
}
執行效果和 ls -al /etc/passwd 一樣
int execlp(const char*path,const cahr * arg1,...)
參數:
arg1-argn:被執行程序所需的命令行參數,含程序名,以空指針NULL結束
path:被執行程序名(不含路徑,將從path環境變量中查找改程序
int execv(const char * path,char *const argv[])
參數;
path:被執行程序名(含路徑)
argv[]:所需命令行參數組。
#include <stdlib.h>
int system(const char*string)
功能:調用fork產生子進程,由子進程調用/bin/sh -c string 來執行string所代表的命令。
eg:system.c
#include<stdlib.h>
int main(void)
{
system("ls -al /etc/pawwsd");
}
進程等待
#include<sys/types.h>
#include<sys/wait.h>
pid_ wait(int status)
功能:阻塞該進程,直到其某個子進程退出。
eg:
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <math.h>
/*
*
* */
int main(void)
{
pid_t child;
/* 創建子進程*/
if((child=fork())==-1)
{
printf("Fork Error : %s\n", strerror(errno));
exit(1);
}
else
{
if(child==0) // 子進程
{
printf("the child process is run\n");
sleep(1); //子進程睡眠一秒,但並沒有去運行父進程
printf("I am the child: %d\n", getpid());
exit(0);
}
else //父進程
{
wait(NULL); //等到子進程退出,父進程纔會運行
printf("the father process is run\n");
printf("I am the father:%d\n",getpid());
return 0;
}
}
}