philosopher.c

来自「在linux下实现编制模拟“五个哲学家”问题的程序」· C语言 代码 · 共 103 行

C
103
字号
#include<stdlib.h>#include<stdio.h>#include<unistd.h>#include<signal.h>#include<string.h>#include"lock.h"#include "lock.c" #define N 5pid_t cpid[5];static char* forkfile[5]={"fork0","fork1","fork2","fork3","fork4"};static void sig_quit(int signo){	if(signo==SIGQUIT||signo==SIGINT)	{		int i;		for(i=0;i<N;i++)		{			unlock(forkfile[i]);			remove(forkfile[i]);			kill(cpid[i],SIGQUIT);		}		exit(0);	}}static void takefork(int i){	if(i==N-1)	{		lock(forkfile[0]);		lock(forkfile[i]);	}	else	{		lock(forkfile[i]);		lock(forkfile[(i+1)%N]);	}}static void think(int i,unsigned int time){	printf("Philosopher %d is thinking.\n",i);	sleep(time);}static void eat(int i,unsigned int time){	printf("Philosopher %d is eating.\n",i);	sleep(time);}static void putfork(int i){	if(i==N-1)	{		unlock(forkfile[0]);		unlock(forkfile[i]);	}	else	{		unlock(forkfile[i]);		unlock(forkfile[(i+1)%N]);	}}int main(int argc,char* argv[]){	unsigned int time;	if(argc==1) time=2;	else if(argc==3&&strcmp(argv[1],"-t")==0)	{		time=(unsigned int)atoi(argv[2]);	}	else	{		printf("Usage:philosopher [-t] time\n");		exit(0);	}	if(signal(SIGQUIT,sig_quit)<0)	{		printf("SIGQUIT error\n");exit(1);	}	if(signal(SIGINT,sig_quit)<0)	{		printf("SIGQUIT error\n");exit(1);	}	int i;	for(i=0;i<N;i++)	{		if((cpid[i]=fork())<0)		{	printf("fork error\n");exit(1);}		else if(cpid[i]==0)		{			sleep(i);			while(1)			{				think(i,time);				takefork(i);				eat(i,time);				putfork(i);			}		}	}	while(1)		pause();}	

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?