1、用父子进程复制一张图片
#include<stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <strings.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/wait.h>
/*思路:父进程阻塞,先用子进程读取图片前半部分,
*成功后将返回值传回父进程
*如果子进程复制前半部分成功,
*解除父进程的阻塞状态,
*并从文件的中间位置开始继续向下读取
*/
int main(int argc, const char *argv[])
{
int fd = open("1.jpg",O_RDONLY);//open picture
umask(0);
int fp = open("2.jpg",O_WRONLY|O_CREAT|O_TRUNC,0664);
if(fd < 0)
{
perror("fd open");
return -1;
}
if(fp < 0)
{
perror("fp open");
return -1;
}
off_t len = lseek(fd,0,SEEK_END);
pid_t cpid = fork();//create child
if(cpid > 0)//father
{
int wstatus;
pid_t wpid = wait(&wstatus);
wstatus = (wstatus & 0xff00)>>8;
if(1 == wstatus)//child write success
{
lseek(fd,len/2,SEEK_SET);
lseek(fp,len/2,SEEK_SET);
ssize_t res = 0;
char buf[3] = "";
for(int i = 0; i < len/2;i ++)
{
bzero(buf,sizeof(buf));
res = read(fd,buf,sizeof(buf));
if(0 == res)
break;
write(fp,buf,res);
}
}
else
printf("father failed\n");
}
else if(0 == cpid)//child
{
if(fd != -1)
{
lseek(fd,0,SEEK_SET);
lseek(fp,0,SEEK_SET);
ssize_t res = 0;
char buf[3] = "";
for(int i = 0; i < len/2;i ++)
{
bzero(buf,sizeof(buf));
res = read(fd,buf,sizeof(buf));
if(0 == res)
break;
write(fp,buf,res);
}
exit(1);
}
else
{
printf("child failed \n");
exit(0);
}
}
else if(cpid < 0)
{
perror("fork");
return -1;
}
return 0;
}
2、验证运行到waitpid非阻塞形式时,若子进程没退出,则子进程会不会变成僵尸进程
不会
#include<stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <string.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
pid_t wpid = fork();//creat child
if(wpid > 0)
{
int wstatus;
sleep(4);
pid_t get_pid = waitpid(wpid,NULL,WNOHANG);
printf("get_pid = %d wstatus = %d %d \n",get_pid,wstatus,WEXITSTATUS(wstatus));
while(1)
{
printf("father : %d %d __%d__\n",getpid(),wpid,__LINE__);
sleep(1);
}
}
else if(0 == wpid)
{
int i = 0;
while(i < 3)
{
printf("child : %d %d\n",getppid(),getpid());
i++;
sleep(1);
}
printf("child exit\n");
//exit(1);
}
else
{
perror("fork");
return -1;
}
while(1)
sleep(1);
return 0;
}
3、创建孤儿进程和僵尸进程
if(wpid > 0)
{
int wstatus;
sleep(4);
pid_t get_pid = waitpid(-1,NULL,WNOHANG);
printf("get_pid = %d wstatus = %d %d \n",get_pid,wstatus,WEXITSTATUS(wstatus));
printf("father : %d %d __%d__\n",getpid(),wpid,__LINE__);
exit(0);
}
else if(0 == wpid)
{
int i = 0;
while(i < 3)
{
printf("child : %d %d\n",getppid(),getpid());
i++;
sleep(1);
exit(0);
}
}
if(wpid > 0)
{
int wstatus;
sleep(4);
pid_t get_pid = waitpid(-1,NULL,WNOHANG);
printf("get_pid = %d wstatus = %d %d \n",get_pid,wstatus,WEXITSTATUS(wstatus));
printf("father : %d %d __%d__\n",getpid(),wpid,__LINE__);
exit(0);
}
else if(0 == wpid)
{
sleep(3);
while(1)
{
printf("child : %d %d\n",getppid(),getpid());
sleep(1);
}
}