1.文件的读写操作与目录文件
实验任务及要求:编写程序,将当前目录下的文件夹dir1下的所有普通文件依次拷贝至当前目录下的文件夹dir2中,且保持文件名不变。要求:不考虑递归情形,不能使用system函数或exec系列函数。
#include<unistd.h> #include<sys/stat.h> #include<fcntl.h> #include<stdio.h> #include<sys/types.h> #include<string.h> #include<dirent.h> int main() { DIR *dir; struct dirent *ptr; dir=opendir("./dir1"); int fdsrc,fddes,nbytes; int flags =O_RDONLY| O_CREAT|O_WRONLY; int z; char buf[20],*des; char *des2; char des3[20]={'\0'}; strcpy(des3,"dir1/"); char des4[20]={'\0'}; strcpy(des4,"dir2/"); char *des5; while((ptr=readdir(dir))!=NULL){ if(ptr->d_type==8){ des=ptr->d_name; printf("%s \n",des); des2=strcat(des3,des); printf("%s \n",des2); fdsrc=open(des2,O_RDONLY); if(fdsrc<0) return 1; des5=strcat(des4,des); printf("%s \n",des5); fddes=open(des5,flags,S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH); while((nbytes=read(fdsrc,buf,20))>0) { z=write(fddes,buf,nbytes); if(z<0){ perror("WRONG!!!"); return 1; } } close(fdsrc); close(fddes); printf("----SUCCESS----\n"); } } closedir(dir); return 0; }
注:需要的目录及文件需要读者自行创建。
2.并发执行以及僵尸进程的避免
实验要求:程序设计要体现子进程与父进程并发执行的效果(即父子进程交替执行各自的printf语句),并且子进程退出后父进程才退出;还应该避免子进程变为僵尸进程。
#include<stdio.h> #include<stdlib.h> #include<unistd.h> #include<sys/types.h> #include<sys/wait.h> int main() { pid_t pid; int i; pid=fork(); if(pid==0) { for(i=0; i<10; i++) { printf("This is the child process, pid: %d\n", getpid()); sleep(1); } exit(0); } else if(pid>0) { waitpid(pid,NULL,0); for(i=0; i<5; i++) { printf("This is the parent process, pid: %d\n", getpid()); sleep(5); } } return 0; }
子进程用fork()函数创建并用结构体pid_t 声明的变量接受返回值,返回值就是子进程的pid号,如果进程号小于0说明该进程创建失败,如果等于0执行的是子进程反之是父进程。
3.子进程的创建和wait的使用
实验要求:子进程执行gedit命令,弹出文本编辑窗口,用户可随意输入一些内容;此过程中,父进程并发执行ping命令,进行20次网络连通测试之后,输出一条提示语句“已ping20次,完成测试任务!”;父进程继而执行wait或waitpid函数,等待子进程的结束,即等待用户关闭gedit命令所产生的文本编辑窗口;子进程正常结束后,父进程利用WIFEXITED、WEXITSTATUS一对宏,捕获子进程的退出码并输出。
#include<stdio.h> #include<stdlib.h> #include<sys/wait.h> #include<sys/types.h> #include<unistd.h> int main() { pid_t pid; pid=fork(); int stat; if(pid==0){ system("gedit"); } else{ system("ping -c 20 100.64.0.4"); printf("-----ping statistics!!------\n"); waitpid(pid,&stat,0); if(WIFEXITED(stat)){ printf("child pid is %d, exited with code %d\n:",getpid(), WEXITSTATUS(stat)); } } return 0; }
这里用system函数可以执行linux指令与之相对应的exec函数族也可以但是exec函数族执行后并不执行在此之后的语句而system函数可以。