linux 进程 fork wait函数

fork:创建子进程

wait:父进程等待子进程结束,并销毁子进程,如果父进程不调用wait函数,子进程就会一直留在linux内核中,变成了僵尸进程。

fork函数的详细说明:fork

wait函数详细说明参考:wait

例子1:不注释掉exit(0)的话,子进程不会执行到printf("end pid: %d\n", getpid());这行。

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <wait.h>//wait function int main(){
pid_t pid; pid = fork(); if(pid == 0){
printf("child process : %d\n", getpid());
//exit(0);
}
else{
int status;
pid_t waitpid; printf("parent process : childpid=%d , mypid=%d\n",pid, getpid());
waitpid = wait(&status);
printf("waitpid:%d\n", waitpid);
}
printf("end pid: %d\n", getpid());
return 0;
}

github源代码

例子2:父进程和子进程之间,值是不共有的,你是你的,我是我的。

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h> int main(){
pid_t pid;
int i = 100; pid = fork(); if(pid == 0){
printf("child process : %d\n", getpid());
i += 500;
}
else{
printf("parent process : childpid=%d , mypid=%d\n",pid, getpid());
i += 1024;
}
printf("i=%d\n", i); return 0;
}

github源代码

例子3:线程之间,值是共有的。

#include <stdio.h>
#include <unistd.h>//sleep function
#include <pthread.h> int global_val = 0; void* sub_thread(void *data){
int* val = (int*)data; printf("sub_thread : val=%d\n", *val); for(int i = 0; i < 10; ++i){
global_val++;
printf("sub_thread : i=%d, g=%d\n", i, global_val);
sleep(1);
}
return NULL;
} int main(){
pthread_t th;
void* th_ret;
int arg = 200; if(pthread_create(&th, NULL, sub_thread, (void*)&arg) != 0){
perror("pthread_create");
return 1;
} for(int i = 0; i < 10; ++i){
global_val++;
printf("main: i=%d, g=%d\n", i, global_val);
sleep(1);
} if(pthread_join(th, &th_ret) != 0){
perror("pthread_join");
return 1;
} return 0;
}

github源代码

编译时需要加 -pthread

g++ -g process-5-thread.cpp -std=c++11 -pthread

c/c++ 学习互助QQ群:877684253

本人微信:xiaoshitou5854

最新文章

  1. 关于VS2010无法编译问题
  2. vs2015 企业版 专业版 密钥
  3. UDP通讯程序设计
  4. hdu 1176 免费馅饼(动态规划)
  5. Java中的static关键字解析(转自海子)__为什么main方法必须是static的,因为程序在执行main方法的时候没有创建任何对象,因此只有通过类名来访问。
  6. [Python爬虫笔记][随意找个博客入门(一)]
  7. Android中使用开源框架EventBus3.0实现Fragment之间的通信交互
  8. 阿里云AliYun表格存储(Table Store)相关案例
  9. [COGS 1799][国家集训队2012]tree(伍一鸣)
  10. 如何在linux上构建objective-c程序
  11. C# 开发ModBus的服务器程序 实现ModBus数据总站 搭建自定义的Modbus服务器 同时支持tcp和rtu
  12. 20165215 2017-2018-2 《Java程序设计》第3周学习总结
  13. hdu1875 畅通工程再续 并查集/最小生成树
  14. 安装sublime3
  15. python实现的摩斯电码解码\编码器
  16. 观察者模式 - Java 实现1(使用JDK内置的Observer模式)
  17. Centos7网络配置(VMware)
  18. 一、flex布局教程:语法篇
  19. vmware安装64位系统“此主机支持 Intel VT-x,但 Intel VT-x 处于禁用状态”的问题
  20. Part01、memcache 缓存

热门文章

  1. Ubuntu12.04中的虚拟机安装Ubuntu16.04,并实现远程控制16.04
  2. 一张图看懂STM32芯片型号的命名规则
  3. HBase之Table.put客户端流程
  4. java代码之美(2)---Java8 Stream
  5. 正则表达式与H5表单
  6. asp.net core 系列 21 EF现有数据库进行反向工程
  7. Shiro中的授权问题
  8. Flink生成Parquet格式文件实战
  9. 【Linux】Rsync的剖析与使用
  10. 第58章 Profile Service - Identity Server 4 中文文档(v1.0.0)