- fork
C语言用fork()创建一个子进程时,子进程会复制父进程,子进程会从fork()函数的调用出返回。子进程对于fork()函数的返回值是0,父进程返回值是子进程的PID,如果创建子进程失败,fork()返回值小于0。
子进程不一定会比父进程执行的慢,当父进程创建子进程时,子进程会和父进程抢占CPU的资源。
下面父进程执行200次循环,子进程执行20次循环,少于父进程执行的循环次数,所以一般子进程会比父进程执行的快一些。
#include <stdio.h>
#include <sys/types.h>
#define MAX_COUNT 200
void ChildProcess(void); /* child process prototype */
void ParentProcess(void); /* parent process prototype */
void main(void)
{
pid_t pid;
pid = fork();
if (pid < 0)
printf("fork failed");
else if (pid == 0)
ChildProcess();
else
ParentProcess();
}
void ChildProcess(void)
{
int i;
for (i = 1; i <= 20; i++)
printf(" This line is from child, value = %d\n", i);
printf(" *** Child process is done ***\n");
}
void ParentProcess(void)
{
int i;
for (i = 1; i <= MAX_COUNT; i++)
printf("This line is from parent, value = %d\n", i);
printf("*** Parent is done ***\n");
}
*wait
调用wait,父进程会等待子进程完成后再执行。wait的返回值是父进程等待的子进程的PID。
#include <stdio.h>
#include <sys/types.h>
#define MAX_COUNT 200
void ChildProcess(void); /* child process prototype */
void ParentProcess(void); /* parent process prototype */
void main(void)
{
pid_t pid;
pid = fork();
if (pid < 0)
printf("fork failed");
else if (pid == 0)
ChildProcess();
else {
ParentProcess();
}
void ChildProcess(void)
{
int i;
for (i = 1; i <= 20; i++)
printf(" This line is from child, value = %d\n", i);
printf(" *** Child process is done ***\n");
}
void ParentProcess(void)
{
int i;
for (i = 1; i <= MAX_COUNT; i++)
printf("This line is from parent, value = %d\n", i);
printf("*** Parent is done ***\n");
}