作业1: 1:使用write 和 read 实现 文件夹拷贝功能,不考虑递归拷贝
//copy文件夹
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<dirent.h>
int main(int argc, const char *argv[])
{
DIR * dir = opendir(argv[1]);
if(dir == NULL)
{
perror("opendir");
return -1;
}
char sys[128]="mkdir ";
strcat(sys,argv[2]);
system(sys);
struct dirent *dnt;
while((dnt = readdir(dir))!=NULL){
if(strcmp(".",dnt->d_name)==0||strcmp("..",dnt->d_name)==0)
{
continue;
}
char r[128] = {0};
strcpy(r,argv[1]);
strcat(r,"/");
strcat(r,dnt->d_name);
int rfp = open(r,O_RDONLY);
if(rfp==-1){
perror("open1");
return -1;
}
char w[128] = {0};
strcpy(w,argv[2]);
strcat(w,"/");
strcat(w,dnt->d_name);
struct stat *mode;
int stat1 = stat(r,mode);
int wfp = open(w,O_WRONLY|O_CREAT|O_TRUNC,0664);
char temp[1]={0};
while(1)
{
int res = read(rfp,temp,sizeof(temp));
if(res <= 0)
{
break;
}
write(wfp,temp,sizeof(temp));
}
close(rfp);
close(wfp);
}
closedir(dir);
return 0;
}
//copy文件
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, const char *argv[])
{
int rfd = open("2.txt", O_RDONLY);
if(rfd == -1) {
perror("open");
return -1;
}
int wfd = open("cpy.txt", O_WRONLY | O_CREAT | O_TRUNC,0664);
if(wfd == -1) {
perror("open");
return -1;
}
char buf[1024] = {0};
int len = 0;
while((len=read(rfd,buf,sizeof(buf)))>0)
{
write(wfd, buf, len);
}
close(rfd);
close(wfd);
return 0;
}
作业2: 使用循环+fork的形式。创建一条进程链,链条上总共有100个进程 要求:程序不崩溃
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, const char *argv[])
{
int num = 100;
for (int i = 0; i < num; i++)
{
int res = fork();
if (res == -1) {
perror("fork");
return 1;
}else if (res == 0) {
printf("子进程 %d PID: %d PPID: %d\n", i+1, getpid(),getppid());
}else
break;
}
sleep(1);
return 0;
}
通过ps -ef查看./a.out的进程信息