zoukankan
html css js c++ java
POSIX 父子进程协同一例
子进程生成fibnacii 父进程输出
#include <sys/types.h> #include <sys/shm.h> #include <sys/stat.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #define MAX_SEQUENCE 10 typedef struct { int fib_sequence[MAX_SEQUENCE]; int sequence_size; }shared_data; int main(int arg, char* argv[]) { if (arg != 2) exit(-1); pid_t pid; int segment_id, n; shared_data* seq; if (!(segment_id = shmget(IPC_PRIVATE, sizeof(shared_data), S_IRUSR|S_IWUSR))) { printf("fail to allocate memory!\n"); fprintf(stderr,"fail to allocate memory!"); exit(-1); } if ((seq = (shared_data*)shmat(segment_id, 0, 0)) == (shared_data *)-1) { printf("fail to attach to segment\n"); fprintf(stderr,"fail to attach to segment %d\n",segment_id); exit(-1); } n = atoi(argv[1]); pid = fork(); if (pid < 0) { printf("fail to set a new process!\n"); fprintf(stderr, "Fork failed!"); exit(-1); } else if (pid == 0) { int i, fir, secd, fib; if (n <= MAX_SEQUENCE) { if (n == 1) { seq->fib_sequence[0] = 0; seq->sequence_size = 1; } else if (n == 2) { seq->fib_sequence[0] = 0; seq->fib_sequence[1] = 1; seq->sequence_size = 2; } else { fir = 0; secd = 1; seq->fib_sequence[0] = 0; seq->fib_sequence[1] = 1; seq->sequence_size = n; for (i = 3; i <= n; i++) { fib = fir + secd; fir = secd; secd = fib; seq->fib_sequence[i-1] = fib; } } } else { exit(-1); } } else { wait(NULL); if (n > MAX_SEQUENCE) { printf("overflow!\n"); exit(-1); } else { int i = 0; while (i < n) { printf("%4d", seq->fib_sequence[i++]); } printf("\n%d", seq->sequence_size); exit(0); } } }
查看全文
相关阅读:
Spring Bean 生命周期
Spring中如何动态注入Bean实例教程
你真的会学习吗——教你如何学习《如何高效学习》
零基础报考软件设计师的经验教训
UDP的优点
科二科三练车,必须明白的10个基础
怎样查看光驱硬盘托架的尺寸
Scala具体解释---------Scala是什么?可伸展的语言!
LeetCode Plus One
LicManager系统对各license类型终端客户机器的监控
原文地址:https://www.cnblogs.com/seebro/p/2476558.html
最新文章
Xamarin开发安装Visual Studio 2015 update2报错的解决办法
Xamarin提示安装包错误解决办法
Arduino可穿戴开发入门教程Windows平台下安装Arduino IDE
Arduino可穿戴开发入门教程Arduino开发环境介绍
Arduino可穿戴开发入门教程LilyPad和LilyPad Simple的介绍
Arduino可穿戴开发入门教程LilyPad介绍
Delphi中TStringList类常用属性方法详解
Delphi 7下使用VT实现树型列表结合控件
Delphi之使用资源文件(Using Resource Files)
Gamma原理及快速实现算法(C/C++)(转)
热门文章
STM32 的加密实现(转)
开方最快算法
Delphi Android程序启动过程
Delphi 悬浮窗口、浮动窗口的实现
USB接口芯片CH375的原理及应用
建立一个属于自己的AVR的RTOS
SiteServer CMS 5.0 源码入门
BeanFactory和ApplicationContext的区别
Spring中ApplicationContext和beanfactory区别
怎样有效管理自己的时间?
Copyright © 2011-2022 走看看