赞
踩
前段时间学习了fork函数创建进程,在fork创建后用execl函数来执行linux下的命令。
fork函数()
一个进程,包括代码、数据和分配给进程的资源。fork()函数通过系统调用创建一个与原来进程几乎完全相同的进程,也就是两个进程可以做完全相同的事,但如果初始参数或者传入的变量不同,两个进程也可以做不同的事。
一个进程调用fork()函数后,系统先给新的进程分配资源,例如存储数据和代码的空间。然后把原来的进程的所有值都复制到新的新进程中,只有少数值与原来的进程的值不同。相当于克隆了一个自己。
用man fork 在linux下查看fork的用法
- #include <unistd.h>
-
- pid_t fork(void);
用法:
#include <sys/types.h>
#include <unistd.h>
pid_t getpid(void);
pid_t getppid(void);
- [fanmaolin@Centeros duojincheng]$ vim testfork.c
-
- 1 /*********************************************************************************
- 2 * Copyright: (C) 2017 fanmaolin<fanmaolinn@gmail.com>
- 3 * All rights reserved.
- 4 *
- 5 * Filename: testfork.c
- 6 * Description: This file
- 7 *
- 8 * Version: 1.0.0(05/09/2017)
- 9 * Author: fanmaolin <fanmaolinn@gmail.com>
- 10 * ChangeLog: 1, Release initial version on "05/09/2017 07:28:18 PM"
- 11 *
- testfork.c
- 12 ********************************************************************************/
- 13
- 14 #include <sys/types.h>
- 15 #include <unistd.h>
- 16 #include <stdio.h>
- 17 int main ()
- 18 {
- 19 pid_t fpid=fork(); //fpid表示fork函数返回的值
- 20 int count=0;
- 21
- 22 if (fpid < 0)
- 23 printf("error in fork!");
- 24 else if (fpid == 0)
- 25 {
- 26 printf("我是子进程\n");
- 27 printf("i am the child process, my process id is %d\n",getpid());
- 28 printf("My Parents's process id is %d\n",getppid());
- 29 count++;
- 30 }
- 31 else
- 32 {
- 33 printf("我是父进程\n");
- 34 printf("i am the parent process, my process id is %d\n",getpid());
- 35 count++;
- 36 sleep(1);//因为不确定父子进程谁会先执行,加个延时保证父进程先执行
- 37 }
- 38 printf("统计结果是: %d\n",count);
- 39 return 0;
- 40 }

- 36 #ifdef SLEEP
- 37 sleep(1);
- 38 #endif
- [fanmaolin@Centeros duojincheng]$ ps aux
- USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
- root 1 0.0 0.1 19364 1264 ? Ss May08 0:03 /sbin/init
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。