fork()系统调用
fork的作用是根据一个现有的进程复制出一个新 进程,原来的进程称为父进程(Parent Process) ,新进程称为子进程(Child Process)。系统中 同时运行着很多进程,这些进程都是从最初只有一个进程开始一个一个复制出来的。在Shell下输入 命令可以运行一个程序,是因为Shell进程在读取用户输入的命令之后会调用fork复制出一个新 的Shell进程,然后新的Shell进程调用exec执行新的程序。例如:在Shell提示符下输入命令ls,首先fork创建子进程,这时父进程仍在执行/bin/bash程序,然后子进程调用exec执行新的程序/bin/ls除了子进程和父进程的进程ID不同,其他资源一模一样。——创建子进程
- 函数原型:
#include<sys/types.h>#include <unistd.h>pid_t fork(void);
返回值信息:(一次调用两次返回的性质)
fork调用失败则返回-1,
成功调用后父进程中返回值为子进程的pid,在子进程中返回值为1
其执行顺序不定!特点:调用一次,返回两次。命令设置gdb
setfollow-fork-mode child 在fork之后跟踪子进程set follow-fork-mode parent 则是跟踪父进程,然后用run命令,看到的现象是父进程一直在运行
demo:
#include <sys/types.h>#include <unistd.h>#include <stdio.h>#include <stdlib.h>#include <erron.h>int main(int argc, char **argv){pid_t m_pid;m_pid = fork();if (pid < 0){perror("fork failed");exit(1);}if (m_pid == 0){printf("i am child!
");}else {printf("i am parent!
");}return 0;}本文永久更新链接地址:http://www.linuxidc.com/Linux/2017-01/140047.htm