news 2026/1/9 23:13:20

Linux进程的等待

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
Linux进程的等待

一、进程等待的必要性

二、进程等待的方法和概念

三、阻塞与非阻塞等待

3.1进程的阻塞等待:

int main() { pid_t pid; pid = fork(); if(pid < 0){ printf("%s fork error\n",__FUNCTION__); return 1; } else if( pid == 0 ){ //child printf("child is run, pid is : %d\n",getpid()); sleep(5); exit(257); } else{ int status = 0; pid_t ret = waitpid(-1, &status, 0);//阻塞式等待,等待5S printf("this is test for wait\n"); if( WIFEXITED(status) && ret == pid ){ printf("wait child 5s success, child return code is :%d.\n",WEXITSTATUS(status)); }else{ printf("wait child failed, return.\n"); return 1; } } return 0; }

3.2进程的非阻塞等待:

#include <stdio.h> #include <stdlib.h> #include <sys/wait.h> #include <unistd.h> #include <vector> typedef void (*handler_t)(); // 函数指针类型 std::vector<handler_t> handlers; // 函数指针数组 void fun_one() { printf("这是⼀个临时任务1\n"); } void fun_two() { printf("这是⼀个临时任务2\n"); } void Load() { handlers.push_back(fun_one); handlers.push_back(fun_two); } void handler() { if (handlers.empty()) Load(); for (auto iter : handlers) iter(); } int main() { pid_t pid; pid = fork(); if (pid < 0) { printf("%s fork error\n", __FUNCTION__); return 1; } else if (pid == 0) { // child printf("child is run, pid is : %d\n", getpid()); sleep(5); exit(1); } else { int status = 0; pid_t ret = 0; do { ret = waitpid(-1, &status, WNOHANG); // ⾮阻塞式等待 if (ret == 0) { printf("child is running\n"); } handler(); } while (ret == 0); if (WIFEXITED(status) && ret == pid) { printf("wait child 5s success, child return code is :%d.\n", WEXITSTATUS(status)); } else { printf("wait child failed, return.\n"); return 1; } } return 0; }
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2025/12/16 21:50:54

HuggingFace自定义模型接入Anything-LLM实战

掌控你的AI大脑&#xff1a;HuggingFace自定义模型接入Anything-LLM实战 在一家初创企业的技术晨会上&#xff0c;法务同事上传了一份长达80页的并购协议PDF&#xff0c;然后问&#xff1a;“这份合同里关于竞业禁止的条款具体覆盖哪些岗位&#xff1f;” 如果是过去&#xff0…

作者头像 李华
网站建设 2026/1/1 7:44:24

Python爬虫实战:利用最新技术从交易所API爬取比特币/加密货币价格与交易数据

引言 在数字货币的浪潮中,获取实时、准确的加密货币数据对于投资者、分析师和开发者至关重要。本文将详细介绍如何使用Python爬虫技术从各大交易所API获取比特币及其他加密货币的价格与交易数据,并进行基本的行情分析。我们将使用最新的Python库和技术栈,包括异步请求、数据…

作者头像 李华
网站建设 2025/12/16 21:46:07

电影推荐系统架构图](https://fakeimg.pl/600x200/ff0000/000?text=SystemArchitecture

hadoop电影推荐系统 大数据电影推荐系统源码 技术栈:javaspringbootlayuihadoop 数据集:豆瓣电影 推荐思路:用户注册登录后浏览电影&#xff0c;对电影进行评分&#xff0c;算法模块定时执行&#xff0c;从mysql读取数据上传到hdfs&#xff0c;并通过执行mapreduce实现的基于用…

作者头像 李华
网站建设 2025/12/27 1:28:15

Kubernetes 环境 NFS 卡死问题排查与解决纪要

Kubernetes 环境 NFS 卡死问题排查与解决纪要 一、事件背景 在 Kubernetes 集群运行过程中&#xff0c;xxxx 命名空间内多个业务 Pod 出现启动异常&#xff0c;部分 Pod 长时间处于 CreateContainerError 或 ContainerCreating 状态&#xff0c;重建 Pod、重启业务均无法恢复。…

作者头像 李华