作业一,父进程拷贝图片前半部分,子进程拷贝图片后半部分
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>
#include <sys/wait.h>
int main(int argc, const char *argv[])
{
//已读方式打开原件
int fd=open("./Piano3_8k.jpg",O_RDONLY);
if(-1==fd)
{
perror("open");
}
//获取数据长度
off_t offset=lseek(fd,0,SEEK_END);
//已写方式打开复印件
int fd1=open("./copy.jpg",O_WRONLY|O_CREAT|O_TRUNC,0777);
if(-1==fd1)
{
perror("open");
}
//创建子进程
pid_t cpid=fork();
//前半部分复制,父进程
if(cpid>0)
{
wait(NULL);
lseek(fd,0,SEEK_SET);
lseek(fd1,0,SEEK_SET);
char c;
for(int i=0;i<offset/2;i++)
{
read(fd,&c,1);
write(fd1,&c,1);
}
printf("前半部分成功复制!!\n");
}
//后半部分,子进程
else if(0==cpid)
{
lseek(fd,offset/2,SEEK_SET);
lseek(fd1,offset/2,SEEK_SET);
char c;
for(int j=offset/2;j<offset;j++)
{
read(fd,&c,1);
write(fd1,&c,1);
}
printf("后半部分成功复制!!\n");
exit(0);
}
close(fd1);
close(fd);
return 0;
}
//结果展示
/*
linux@linux:~/Desktop/demo3/day4$ gcc work.c
linux@linux:~/Desktop/demo3/day4$ ./a.out
前半部分成功复制!!
后半部分成功复制!!
*/
2. 验证运行到waitpid非阻塞形式时,若子进程没退出,则子进程会不会变成僵尸进程
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
int main()
{
pid_t cpid=fork();
if (cpid == 0)
{
printf("子进程pid=%d\n",getpid());
}
else if (cpid > 0)
{
waitpid(0,NULL,WNOHANG);
printf("父进程pid=%d\n",getppid());
}
while(1)
{
sleep(1);
}
return 0;
}
不会变成僵尸进程
3.创建孤儿进程
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
int main()
{
pid_t cpid=fork();
if (cpid == 0)
{
sleep(1);
printf("子进程pid=%d\n",getpid());
}
else if (cpid > 0)
{
printf("父进程pid=%d\n",getppid());
exit(0);
}
while(1)
{
sleep(1);
}
return 0;
}
4.创建僵尸进程
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <time.h>
int main()
{
pid_t cpid=fork();
if (cpid == 0)
{
printf("子进程pid=%d\n",getpid());
exit(0);
}
else if (cpid > 0)
{
sleep(1);
printf("父进程pid=%d\n",getppid());
}
while(1)
{
sleep(1);
}
return 0;
}
~