Linux多进程编程

创建进程
所需头文件:

#include <unistd.h>

#include <sys/types.h>

函数:
pid_t fork(); 创建一个子进程,在子进程中返回0,在父进程中返回子进程ID,出错则返回-1。
pid_t vfor(); 创建一个子进程,与fork()相似;区别如下:
fork()子进程拷贝父进程数据段、堆栈段,vfork()则是共享;
fork()父子进程执行顺序不确定,vfork()是先执行完子进程再执行父进程。

pid_t getpid(); 返回当前进程ID
pid_t getppid(); 返回父进程ID

进程等待
头文件:

#include <sys/wait.h>

函数:
pid_t wait(int *status); 等子进程结束之后才运行。
status:接收子进程返回状态

pid_t waitpid(pid_t pid, int *status, int options); 与waitpid()相似。
pid:指定的进程号,当pid=-1时等待任何子进程,相当于wait();
status:用于接收进程返回状态;
option:为WNOHANG时若无任何已结束的子进程则马上返回,不予以等待;为WUNTRACES时若子进程暂停则马上返回,不予以理会结束状态。

例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//使用vfor函数创建子进程
//龙昌博客:http://www.xefan.com
#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;
int i = 0;

/* 创建子进程 */
if((child=vfork())==-1)
{
printf("Fork Error : %s\n", strerror(errno));
exit(1);
}
else
{
if(child > 0)
{
i++;
printf("I am the father: %d ;i=%d\n", getpid(), i);
exit(0);
}
else
{
i++;
printf("I am the child:%d ;i=%d\n",getpid(), i);
sleep(1);
exit(0);
}
}
}