一、頭文件
#include <unistd.h>
二、getpid()函數
pid_t getpid(void); // 獲取本進程 ID 。
三、getppid()函數
pid_t getppid(void); // 獲取父進程 ID 。
四、fork()函數
pid_t fork(void); // 創建子進程
fork的奇妙之處在於它被調用一次,卻返回兩次,它可能有三種不同的返回值:
1,在父進程中, fork 返回新創建的子進程的 PID;
2,在子進程中, fork 返回 0 ;
3,如果出現錯誤, fork 返回一個負值。
例1:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
void main()
{
pid_t pid;
//此時僅有一個進程
pid = fork();
//此時已經有兩個進程在同時運行
if (pid < 0)
printf("error in fork!");
else if (pid == 0)
printf("I am the child process, ID is %d\n", getpid());
else
printf("I am the parent process, ID is %d\n", getpid());
}
運行結果: 輸出I am the parent process, ID is 5562
I am the child process, ID is 5563
說明: 在 pid = fork() 之前,只有一個進程在執行,但是在這條語句執行之後, 就變成兩個進程在執行了,這兩個進程的共享代碼段,將要執行的下一條語句都是 if (pid == 0)。兩個進程中,原來就存在的那個進程被稱作“父進程”,新 出現的那個進程被稱作“子進程”,父子進程的區別在於進程標識符(PID)不同。
例2:
#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()函數
pid_t vfork(void); //功能:創建子進程
fork PK vfork
區別:1. fork :子進程拷貝父進程的數據段
vfork :子進程與父進程共享數據段
2. fork : 父、子進程的執行次序不確定
vfork : 子進程先運行,父進程後運行
六、exec 函數族
exec用被執行的程序替換調用它的程序。
區別:fork創建一個新的進程,產生一個新的PID。
exec啓動一個新程序,替換原有的進程,因此進程的PID不會改變。
6.1 execl
int execl(const char *path, const char *arg1, ...)
參數:path : 被執行程序名(含完整路徑)。
arg1 -- argn : 被執行程序所需的命令行參數,含程序名。已空指針(NULL)結束。
例:
#include <stdio.h>
#include <unistd.h>
void main()
{
execl("/bin/ls", "ls", "-al", "/etc/passwd", (char*)0);
}
6.2 execlpint execlp(const char* path, const char* arg1, ...)
參數:
path:被執行程序名(不含路徑,將從path環境變量中查找該程序)
arg1 -- argn : 被執行程序所需的命令行參數,含程序名。以空指針(NULL)結束。
例:
#include <stdio.h>
#include <unistd.h>
void main()
{
execlp("ls", "ls", "-al", "/etc/passwd", (char*)0);
}
6.3 execvint execv(const char* path, char* const argv[])
參數:
path : 被執行程序名(含完整路徑)
argv[] : 被執行程序所需的命令行參數數組。
例:
#include <stdio.h>
#include <unistd.h>
void main()
{
char* argv[] = {"ls", "-al", "/etc/passwd", (char*)0};
execv("ls", argv);
}
七、 system 函數int system(const char* string)
功能:調用 fork 產生子進程,由子進程來調用 /bin/sh -c string 來執行參數
string 所代表的命令。
例:
#include <stdio.h>
#include <unistd.h>
void main()
{
system("ls -al /etc/passwd");
}
八 進程等待8.1 wait
pid_t wait(int* status)
功能:阻塞該進程,直到其某個子進程退出。
例:
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
void main()
{
pid_t pc,pr;
pc = fork();
if (pc == 0)
{
printf("This is child process with pid of %d\n", getpid());
sleep(10);
}
else if (pc > 0)
{
pr = wait(NULL);
printf("I catched a child process with pid of %d\n", pr);
}
exit(0);
}