fork调用
来源:互联网 发布:淘宝商品优惠券 编辑:程序博客网 时间:2024/06/03 18:09
#include <sys/types.h>#include <sys/stat.h>#include <sys/uio.h>#include <unistd.h>#include <fcntl.h>#include <string.h>#include <sys/wait.h>#include <stdio.h>#include <stdlib.h>int main(){ char buf[100] = {0}; pid_t child_pid; int fd = 0; int status = 0; if ((fd = open("temp", O_CREAT|O_RDWR|O_TRUNC, 0664)) == -1) { perror("创建文件"); exit(1); } strcpy(buf, "父进程数据"); if ((child_pid = fork()) == 0) { printf("fork() return value in children process : %d\n", child_pid); strcpy(buf, "子进程数据"); puts("child process is running!"); printf("child process pid = %d\n", getpid()); printf("father process pid = %d\n", getpid()); int write_bytes = write(fd, buf, strlen(buf)); close(fd); exit(0); } else { printf("fork() return value in parent process : %d\n", child_pid); puts("father process is running!"); printf("father process pid = %d\n", getpid()); printf("child process pid = %d\n", getpid()); int write_bytes = write(fd, buf, strlen(buf)); close(fd); } wait(&status); return 0;}
fork() return value in parent process : 2948
father process is running!
father process pid = 2947child process pid = 2947
fork() return value in children process : 0
child process is running!
child process pid = 2948
father process pid = 2948
fork系统调用有两个函数,分别是fork和vfork,fork系统调用可以创建一个子进程
pid_t fork(void);
pid_t vfork(void);
pid_t是用来保存进程PID信息的结构体,当调用执行成功时,该调用对父进程返回子进程的PID,对子进程返回0。若调用失败,返回-1,子进程不创建,vfork函数形式相同,区别是vfork函数创建子进程时,不复制父进程的上下文。
从上面代码段的执行结果来看,父进程调用子进程后,父进程由内核状态转为用户转改,子进程开始执行并输出了消息,然后子进程调用exit函数进入僵死状态,父进程由用户状态重新回到内核状态,并输出信息,最后父进程等待子进程结束,父进程结束
子进程是从fork调用出开始执行的,因此fork不会被执行两次,代码中的fork返回给父进程和子进程的值不同,因此可以作为区分父进程和子进程的区别
阅读全文
0 0
- fork调用
- fork系统调用
- fork()系统调用
- linux fork系统调用
- fork系统调用
- 系统调用分析:fork
- Linix fork系统调用
- fork调用拷贝缓冲区
- linux 系统调用fork
- fork 系统调用
- Linux fork()系统调用
- fork系统调用
- fork()系统调用函数
- fork调用拷贝缓冲区
- fork系统调用
- 浅析fork系统调用
- 系统调用fork()函数
- fork系统调用过程
- 基于MongoDB数据库的Java程序实现增删改查功能
- js获取视频时长
- Win10 64位下GPU版本MXNet+Tensorflow 1.3.0的安装
- (原创分享C# MVC)微信支付之公众号支付教程
- Spring使用Java类定义Bean信息
- fork调用
- 你不知道的产品分析法则
- 【笔记】PackageManager获取App基本信息实现Apk导出、分享、卸载
- UVa 10474 where is marble?
- Host is not allowed to connect to this MySQL server解决方法
- php对xml的XPath操作
- java学习(9) 匿名内部类
- 树状数组 区间修改区间求和总结
- Qt 调用 Windows 接口实现窗口置顶