进程的创建(c语言)
linux系统下验证程序的并发性,使用c语言fork()函数创建子进程,根据fork()函数特性,操作父子进程,观察父子进程在操作系统管理下执行情况,理解进程的独立性
实验步骤
(1)利用fork()函数创建进程
打开终端并输入以下代码创建实验文件
Charlie@Charlie-PC:~$ cd Desktop
Charlie@Charlie-PC:~/Desktop$ mkdir test
Charlie@Charlie-PC:~/Desktop$ cd test
Charlie@Charlie-PC:~/Desktop/test$ touch hello.c
使用vscode打开hello.c文件并输入以下代码
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
//Practice:How to create a child process?
int main()
{
pid_t pid;
pid_t cid;
//利用getpid函数返回当前进程的id;
printf("Before fork Process id is:%d\n ",getpid());
//利用fork()函数创建子进程;
fork();
printf("After fork,Process id is:%d\n",getpid());
pause(); //暂停程序运行,用于观察该程序在系统中产生的进程
return 0;
}
保存并退出,使用gcc对源文件进行编译。
利用**./命令**运行编译后的文件(ctrl+c停止运行),运行结果如下:
Charlie@Charlie-PC:~/Desktop/test$ ./hello
Before fork Process id is:9833
After fork,Process id is:9833
After fork,Process id is:9834
重新打开一个终端输入ps -al可以查看当前运行的进程状态
Charlie@Charlie-PC:~/Desktop/test$ ps -al
F S UID PID PPID C PRI NI ADDR SZ WCHAN TTY TIME CMD
0 S 1000 9833 9457 0 80 0 - 571 do_sys pts/0 00:00:00 hello
1 S 1000 9834 9833 0 80 0 - 571 do_sys pts/0 00:00:00 hello
4 R 1000 9897 9841 0 80 0 - 4343 - pts/1 00:00:00 ps
执行fork()后创建了一个pid为9834的子进程,子进程的ppid为父进程的pid
(2)fork()函数返回值研究
fork()函数成功执行后在父进程中返回子进程的pid,在子进程中返回值为0
修改代码如下,重新编译、执行,观察终端输出情况
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
pid_t pid,cid;
printf("Before fork Process id is:%d\n ",getpid());
cid = fork();
/*
fork()函数如果成功创建子进程,对于父子进程返回值不一样,
父进程中返回子进程的id,
子进程返回0;
如果创建失败则返回-1
*/