操作系统实验_示例代码_linux.docVIP

  • 56
  • 0
  • 约2.8万字
  • 约 29页
  • 2016-10-19 发布于重庆
  • 举报
操作系统实验_示例代码_linux

《计算机操作系统》 实验指导 苏州科技学院电子与信息工程系 软件教研室 二OO二年九月 示例代码 第一部分 LINUX 操作系统平台 实验一 命令解释程序 示例程序minishell.c //文 件 名 minishell.cpp //功 能 小型SHELL命令解释程序 //开发环境 #define true 1 #define flase 0 #include stdio.h #include string.h #include stdlib.h void main() { char cmdl[80]; char *scwt[]={exit,dir,time}; static int cmdnum=3; //可用的命令数 char cmd[80]; int j,n; while(true) { printf(Please input command: ); gets(cmdl); //取命令行输入 n=strcspn(cmdl, ); //取命令命令部分 if (n0||strlen(cmdl)0) { strncpy(cmd,cmdl,n); cmd[n]=\0; for(j=0;jcmdnum;j++) if (strcmp(cmd,scwt[j])==0) break; if (j==0) //是exit命令? exit(0); if (jcmdnum) //其他合法命令 { system(cmdl); continue; } printf(Bad command!\n); //命令错 } } } 实验二 进程管理 fork()调用示例 #include stdio.h main(){ int p1,p2; while ((p1=fork())==-1); if (p1==0) //是子进程? putchar(b); else //父进程 { putchar(a); } } 实验三 进程间通信 1)pipe()调用示例 #includestdio.h main() { int id,fd[2]; char buf[50],s[50]; pipe(fd); while ((id=fork())==-1); if (id==0) { sprintf(buf,Child is sending message!); write(fd[1],buf,50); exit(0); } else { wait(0); read(fd[0],s,50); printf(%s\n,s); exit(0); } } 2)共享存储器示例shm_sample.c #include stdio.h #include sys/types.h #include sys/ipc.h #include sys/shm.h #define SEGSIZE 100 main(int argc, char *argv[]) { key_t key; int shmid, cntr; char *segptr; if(argc == 1) usage(); /* Create unique key via call to ftok() */ key = ftok(., S); /* Open the shared memory segment - create if necessary */ if((shmid = shmget(key, SEGSIZE, IPC_CREAT|IPC_EXCL|0666)) == -1) { printf(Shared memory segment exists - opening as client\n); /* Segment probably already exists - try as a client */ if((shmid = shmget(key, SEGSIZE, 0)) == -1) { perror(shmget); exit(1); } } else { printf(Creating new shared memory segment\n); } /* Attach (map) the shared memory segment into the current process */ if((segptr = shmat(shmid, 0, 0)) == -1) { perror(s

文档评论(0)

1亿VIP精品文档

相关文档