1.使用fork函数创建一个子进程

需要的头文件及函数原型如下:

#include <sys/types.h>
#include <unistd.h>

       pid_t fork(void);

编写代码如下:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
	pid_t pid;
	pid = getpid();
	fork();

	printf("pid = %d,pid2 = %d\n",pid,getpid());    //pid为父进程的进程ID号,而getpid()是获取当前进程的ID号。
	
	return 0;
}

运行结果如下:

 由于fork函数创建了一个新的子进程,所以fork函数后的语句会执行两次,也就是打印两次进程的pid号。因为printf第一次运行在父进程,所以两个pid的值相等,但printf第二次运行在子进程,所以两个pid就不相等了,也就是说此时的pid2是子进程的进程ID。所以代码可以修改为

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
	pid_t pid;
	pid = getpid();
	printf("before fork pid = %d\n",getpid());    //在这里先把父进程的ID号打印出来;
	fork();
	printf("after fork pid = %d\n",getpid());     //在这里再次打印当前进程的ID号
	if(pid == getpid()){       //如果父进程的ID号和当前进程的ID号相等的话,就表明进入了父进程。
		printf("this is in father,the father pid = %d\n",getpid());
	}else{                    //如果父进程的ID号和当前进程的ID号不相等的话,就表示进入了子进程。
		printf("this is in chird ,the child pid = %d\n",getpid());
	}
	return 0;
}

到此为止,还并没有关心fork的返回值。

fork函数调用成功,返回两次

返回值为0,代表当前进程为子进程,返回值大于零也就是子进程的PID,代表当前进程为父进程。返回值为-1,则代表函数调用失败,即创建子进程失败。

此时修改代码为:

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
	pid_t pid;
	printf("the father pid = %d\n",getpid());
	pid = fork();
	if(pid > 0){
		printf("this is in father,the father pid = %d\n",getpid());
	}else if(pid == 0){
		printf("this is in chird ,the child pid = %d\n",getpid());
	}
	return 0;
}

Logo

更多推荐