Google Code Prettify

2012年12月6日 星期四

C - 利用multiprocess & message passing實作Fibonacci數列




/*****************
程式功能: Fibonacci數列之實作。
程式流程: 執行此程式後輸入一數字,作為Fibonacci數列之個數,由parent process接收該數值,並利用message passing將數值傳給child process,並於child process內實作此數列,將結果傳回parent process後印出。
執行方法: ./prog2
Please enter the size of Fibonacci sequence (m): [value]
******************/
#include <sys/types.h>
#include <sys/msg.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
//message buffer structure, 作為parent&child process間的訊息傳遞物
struct msgbuf {
long mtype;
int size;
int Fib[100];
};
int main ()
{
key_t key;
pid_t pid;
struct msgbuf buf;
int i, n, msqid;
pid = fork(); //create a child process
//report if fork failed
if (pid < 0) {
printf("Fork Failed.\n");
return 1;
}
//Child process
else if (pid == 0) {
//setup the message permission key
if ((key = ftok("prog2.c", 'C')) == -1) {
printf("ftok failed.\n");
return 1;
}
//set the permissions on the queue to 777
if ((msqid = msgget(key, 0777 | IPC_CREAT)) == -1) {
printf("msgget failed.\n");
return 1;
}
//receive the message with the same key from the queue
if (msgrcv(msqid, &buf, sizeof(struct msgbuf) - sizeof (long), 0, 0) == -1) {
printf("msgrcv failed.\n");
return 1;
}
//setup the initial value of Fibonacci sequence
buf.Fib[0] = 0; buf.Fib[1] = 1;
//計算並儲存Fibonacci數列之值,數列個數為使用者輸入之值
for (n = 2; n < buf.size; n++) {
buf.Fib[n] = buf.Fib[n - 1] + buf.Fib[n - 2];
}
//send the message with the key to the queue
if (msgsnd(msqid, &buf, sizeof(struct msgbuf) - sizeof(long), 0) == -1) {
printf("msgsnd failed.\n");
return 1;
}
}
//Parent process
else {
//setup the permission key
if ((key = ftok("prog2.c", 'C')) == -1) {
printf("ftok failed.\n");
return 1;
}
//set the permissions on the queue to 777
if ((msqid = msgget(key, 0777 | IPC_CREAT)) == -1) {
printf("msgget failed.\n");
return 1;
}
//ask user to enter the size of fibonacci sequence
printf("Please enter the size of fibonacci sequence (m): ");
scanf("%d", &buf.size);
//Get the next message with an mtype equal to the specified msgtyp.
buf.mtype = 1;
//send the message with the key to the queue
if (msgsnd(msqid, &buf, sizeof(struct msgbuf) - sizeof(long), 0) == -1) {
printf("msgsnd failed.\n");
return 1;
}
//wait for the child to complete
wait(NULL);
//receive the message with the same key from the queue
if (msgrcv(msqid, &buf, sizeof(struct msgbuf) - sizeof(long), 0, 0) == -1) {
printf("msgrcv failed.\n");
return 1;
}
//print out the result
printf("Fibonacci: ");
for (i = 0; i < buf.size; i++)
printf("%d ", buf.Fib[i]);
putchar('\n');
}
return 0;
}
view raw Fibonacci.c hosted with ❤ by GitHub

沒有留言:

張貼留言