- 前言
- 一、实验目的
- 二、实验工具与设备
- 三、实验预备知识
- 四、实验内容和步骤
- 五、实验代码及步骤截图
为了帮助同学们完成痛苦的实验课程设计,本作者将其作出的实验结果及代码贴至CSDN中,供同学们学习参考。如有不足或描述不完善之处,敬请各位指出,欢迎各位的斧正!
一、实验目的- 了解Linux操作系统的文件系统类系统函数的调用。
- 了解Linux操作系统的进程类系统函数的调用。
装有Linux系统的计算机
三、实验预备知识参见教材系统接口函数调用章节内容
四、实验内容和步骤-
读文件系统函数read命令的使用。
当文件打开后,系统函数调用read()对文件进行读操作。
我在程序中首先打开文件/etc/bashrc,然后将文件中前1024字节的内容读到缓冲区buffer中。
上图为编写的函数,打开文件/etc/bashrc,然后将文件中前1024字节的内容读到缓冲区buffer中。
上图为运行的结果,成功的读取了/etc/bashrc文件的前1024字节的内容。 -
写文件系统函数write的使用。
系统函数write()调用是在文件被open后,从缓冲区buffer将指定字节的内容写到由open返回的文件描述符所指定的文件中。
备份文件,该备份不保护源文件的权限,也不保护与目标文件相同的文件内容。
编写的代码(1)
编写的代码(2)
第一个箭头表示编译成功。
第二个箭头说明目标需要一个文件,不能是一个目录。
第三个箭头表示了运行所需要的格式,即需要源文件的路径以及目标文件的路径。
第四个箭头所指表示成功运行。
验证成功,复制文件到目标路径。 -
创建新进程命令的使用。
创建新进程代码
运行结果:创建进程成功 -
创建守护进程命令的使用。
创建守护进程代码
编译并执行
执行后,每隔三秒会输出一个hello,我们查看其进程号并kill该守护进程,守护进程关闭 -
获取进程标识符与获取父进程标识符命令的使用
获取进程标识符与获取父进程标识符代码
编译成功以及运行结果,正确输出进程号以及父进程号
6-1.c:
#include#include #define rwmode 0 int main() { int fd; char buffer[1024]; int n; if((fd=open("/etc/bashrc",rwmode))==1) perror("Can't open file /etc/bashrc"); else printf("open /etc/bashrc ok!n"); n=read(fd,buffer,sizeof(buffer)-1); buffer[n]=' '; printf("%sn",buffer); close(fd); exit(0); }
其运行截图如下:
6-2.c:
# include# include # include #define resource_mode 0 #define destination_mode 0774 #define FILESIZE 1024 int main(int argc, char *argv[]) { int resource_fd,destination_fd; int readbytes, writtenbytes; char buffer[FILESIZE],*p; if(argc!=3) { printf("Usage:copy from resource file to destination filen %s src_file dest_filen", argv[0]); exit(0); } if((resource_fd=open(argv[1],resource_mode))==-1) { perror("Can't open source file"); exit(0); } if((destination_fd=creat(argv[2],destination_mode))==-1) { perror("Can:t creat destination file"); exit(0); } while(readbytes=read(resource_fd,buffer,FILESIZE)) { p=buffer; if((readbytes==-1)&&(errno!=EINTR)) break; else if(readbytes>0) { while(writtenbytes=write(destination_fd,p,readbytes)) { if((writtenbytes=-1)&&(errno!=EINTR)) break; else if(writtenbytes==readbytes) break; else if(writtenbytes>0) { p+=writtenbytes; readbytes-=writtenbytes; } } if(writtenbytes==-1) break; } } close(resource_fd); close(destination_fd); exit(0); }
其运行截图如下:
6-3.c:
#include#include #include int main() { int pid; printf("Now this is process 1.n"); printf("System calling fork() will start.n"); pid=fork(); if(pid==0) printf("This is child process.n"); else if(pid>0) printf("This is process 1(parent process).n"); else printf("fork failed.n"); printf("The program end.n"); exit(0); }
其运行截图如下:
6-4.c:
#include#include int main() { int pid; pid=fork(); if(pid>0) exit(0); else if(pid<0) { perror("fork error"); exit(-1); } for(;;) { printf("hello...n"); sleep(3); } }
其运行截图如下:
6-5.c:
#include#include #include #include int main(int argc,char *argv[]) { int pid,ppid; pid=getpid(); ppid=getppid(); printf("The process's pid is:%d",pid); printf("n"); printf("The parent process's pid is:%d",ppid); printf("n"); exit(0); }
其运行截图如下:



