runxinzhi.com
首页
百度搜索
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); } } }
相关阅读:
【中山纪念中学六年级模拟赛】方格翻转 题解
高斯消元
net 控件开发资料
使用自定义验证组件库扩展 Windows 窗体
POJ 3032
UVa 10878 Decode the tape
C语言I博客作业03
第十周助教总结
第十二周助教总结
C语言I博客作业06
原文地址:https://www.cnblogs.com/seebro/p/2476558.html
最新文章
Zend_Application
Notepad++插件开发
shell 初始化二进制文件
COMTRADE(IEEE标准电力系统暂态数据交换通用格式STD C37.1111991/1999)文件格式解析
pcap文件格式解析
No resource identifier found for attribute 'XXX' in package XXXXX'问题
Intent、Bundle、ListView,Adapter的应用
android studio中terminal的使用
实现一个简单的播放器——Service,Handle和MediaPlayer的使用
Broadcast的动态注册与静态注册和Notification的使用
热门文章
Android studio的错误记录
VMWare Tools安装——实现主机和虚拟机之间的复制粘贴
【中山纪念中学六年级模拟赛】纸人 题解
2021.03.20【NOIP提高B组】模拟 总结
JZOJ 5409 Fantasy & NOI 2010 超级钢琴 题解
exgcd
2021.03.06【NOIP提高B组】模拟 总结
斜率优化 dp
2021.03.13【NOIP提高A&B组】模拟 总结
矩阵乘法优化递推
Copyright © 2020-2023
润新知