1. 完成拷贝那题
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, const char *argv[])
{
pid_t pid=fork();
int fd_f=open("./011.png",O_RDWR);
int fd_cpy=open("./12.png",O_RDWR|O_CREAT,0664);
int f=lseek(fd_f,0,SEEK_END);
char buf=0;
ssize_t count=0;
if(pid>0)
{
lseek(fd_f,0,SEEK_SET);
lseek(fd_cpy,0,SEEK_SET);
if(count<(f/2))
{
while(1)
{
buf=0;
ssize_t res=read(fd_f,&buf,1);
if(res==0)
{
printf("上半部分完成\n");
break;
}
write(fd_cpy,&buf,res);
count+=res;
}
}
wait(NULL);
}
else if(pid==0)
{
lseek(fd_f,f/2,SEEK_SET);
lseek(fd_cpy,f/2,SEEK_SET);
if(count<f/2)
{
while(1)
{
buf=0;
ssize_t res_w=read(fd_f,&buf,1);
if(res_w==0)
{
printf("下半部分完成\n");
break;
}
write(fd_cpy,&buf,res_w);
count+=res_w;
}
}
}
else
{
return -1;
}
close(fd_f);
close(fd_cpy);
return 0;
}
2. 验证运行到waitpid非阻塞形式时,若子进程没退出,则子进程会不会变成僵尸进程
不会。
3. 创建孤儿进程和僵尸进程
孤儿进程
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, const char *argv[])
{
pid_t pid=fork();
if(pid>0)
{
int i=0;
while(i<3)
{
sleep(1);
printf("父进程\n");
i++;
}
exit(1);
}
else if(pid==0)
{
while(1)
{
sleep(1);
printf("子进程\n");
}
}
else
{
return -1;
}
return 0;
}
僵尸进程
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, const char *argv[])
{
pid_t pid=fork();
if(pid>0)
{
while(1)
{
sleep(1);
printf("父进程\n");
}
}
else if(pid==0)
{
int i=0;
while(i<3)
{
sleep(1);
printf("子进程\n");
i++;
}
}
else
{
return -1;
}
return 0;
}