1. 拷贝一张图片,父进程拷贝一半,子进程拷贝另一半
#include
#include
#include
#include
#include
int main(int argc, const char *argv[])
{
int fd = open("1.png",O_RDONLY);
int fdw = open("p.png",O_RDWR|O_CREAT|O_TRUNC);
off_t offset = lseek(fd,0,SEEK_END);
printf("The total byte of the image is %ld\n",offset);
lseek(fd,0,SEEK_SET);
char c = 0;
printf("Parent %d is copying the first half.\n",getpid());
ssize_t total = 0;
while(1){
ssize_t one = read(fd,&c,1);
write(fdw,&c,1);
total += one;
if(total == offset / 2)
{
printf("Parent copying is done.\n");
printf("fd = %ld fdw = %ld\n",lseek(fd,0,SEEK_CUR),lseek(fdw,0,SEEK_CUR));
break;
}
}
pid_t cpid = fork();
if(cpid == 0){
printf("Child %d is copying the second half.\n",getpid());
while(1){
ssize_t one = read(fd,&c,1);
write(fdw,&c,1);
total += one;
if(total == offset)
{
printf("Child copying is done.\n");
printf("fd = %ld fdw = %ld\n",lseek(fd,0,SEEK_CUR),lseek(fdw,0,SEEK_CUR));
close(fd);
close(fdw);
break;
}
}
}else{
close(fd);
close(fdw);
}
chmod("p.png",S_IRUSR|S_IWUSR);
return 0;
}
2.验证运行到waitpid非阻塞形式时,若子进程没退出,则子进程会不会变成僵尸进程
结果是会的。
#include
#include
#include
#include
#include
int main(int argc, const char *argv[])
{
pid_t cpid = fork();
if(cpid > 0){
int wstatus = 1;
pid_t killed = waitpid(cpid,&wstatus,WNOHANG);
while(1){
printf("parent %d is running\n",getpid());
sleep(1);
}
}else if(cpid == 0){
int child = getpid();
sleep(3);
printf("child %d exiting\n",child);
exit(0);
}else{
return -1;
}
return 0;
}
3. 创建孤儿进程和僵尸进程
orphan
#include
#include
#include
#include
int main(int argc, const char *argv[])
{
pid_t cpid = fork();
if(cpid > 0){
printf("%d Parent %d exited\n",__LINE__,getpid());
exit(0);
}else if(cpid == 0){
while(1){
printf("%d Child %d running\n",__LINE__,getpid());
sleep(1);
}
}else{
return -1;
}
return 0;
}
zombie
#include
#include
#include
#include
int main(int argc, const char *argv[])
{
pid_t cpid = fork();
if(cpid > 0){
while(1){
printf("%d Parent %d is running\n",__LINE__, getpid());
sleep(1);
}
}else if(cpid == 0){
printf("%d Child %d exiting.\n",__LINE__,getpid());
exit(0);
}else{
return -1;
}
return 0;
}