POSIX 父子进程协同一例

子进程生成fibnacii 父进程输出 #include #include #include #include #include #include #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); } } }

转载于:https://www.cnblogs.com/seebro/archive/2011/08/25/2476558.html

你可能感兴趣的:(POSIX 父子进程协同一例)