⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 philosopher.c

📁 unix下实现5个哲学家之间的取食和思考的问题的一个实验
💻 C
字号:
#include"apue.h"#include"lock.h"#include<unistd.h>int main(int argc,char *argv[]){ int t,i; pid_t pid[6]; if(argc>3||argc<1)   err_quit(" usage: philosopher -t <time>"); if(argc==3){   if(strcmp(argv[1],"-t")!=0)   err_sys("input error\n");} if(argc==1){  if(argv[1]=='\0')   t=2; else{    t=*(argv[2])-48;   if(t<0 && t>9)   err_sys(" time error \n"); } } for(i=1;i<6;i++){  if((pid[i]=fork())<0)   err_sys("fork error");  else if (pid[i]==0) continue;//sleep(k);  // k-=2;// exit(7); // if(waitpid(pid[i],NULL,0)!=pid[i])  // err_sys("wait error\n"); }  while(1){  if(pid[1]==0){  printf("the first philosopher is thinking \n");  sleep(t);  lock("2");  lock("1");  printf("the first phiosopher is eating \n");  sleep(t);  unlock("1");  unlock("2");  sleep(t);  }  if(pid[2]==0){  sleep(t);  printf("the second philosopher is thinking \n");  lock("2");  lock("3");  printf("the second phiosopher is eating \n");  sleep(t);  unlock("2");  unlock("3");  sleep(t);} if(pid[3]==0){  sleep(t);  printf("the third philosopher is thinking \n");  lock("4");  lock("3");  printf("the third phiosopher is eating \n");  sleep(t);  unlock("4");  unlock("3");  sleep(t);}if(pid[4]==0){  sleep(t);  printf("the fourth philosopher is thinking \n");  lock("4");  lock("5");  printf("the fourth phiosopher is eating \n");  sleep(t);  unlock("4");  unlock("5");  sleep(t);}if(pid[5]==0){  sleep(t);  printf("the fifth philosopher is thinking \n");  lock("1");  lock("5");  printf("the fifth phiosopher is eating \n");  sleep(t);  unlock("1");  unlock("5");  sleep(t);}//if}//while}

⌨️ 快捷键说明

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