使用文件O函数,拷贝一张图片,父进程拷贝前半部分,子进程拷贝后半部分。不能使用slep函数。
提示:
1.一个进程拷贝完毕后再开始另外一个进程。
2.父子进程各自开各自的文件。
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
int main(int argc, const char *argv[])
{
pid_t pwd=fork();
if(pwd>0)
{
int fp=open("./1.png",O_RDONLY);
if(fp<0)
{
perror("erron");
return -1;
}
int fq=open("./cpy.png",O_RDWR|O_APPEND|O_CREAT,0775);
if(fq<0)
{
perror("erron");
return -1;
}
off_t len=lseek(fp,0,SEEK_END);
lseek(fp,0,SEEK_SET);
printf("len=%ld\n",len);
char str[len/2];
ssize_t ret=0;
ret=read(fp,str,sizeof(str));
write(fq,str,sizeof(str));
close(fp);
close(fq);
}
else if(pwd==0)
{
int fa=open("./1.png",O_RDONLY);
if(fa<0)
{
perror("erron");
return -1;
}
int fb=open("./cpy.png",O_RDWR|O_APPEND|O_CREAT,0775);
if(fb<0)
{
perror("erron");
return -1;
}
off_t len=lseek(fa,0,SEEK_END);
printf("len=%ld\n",len);
lseek(fa,len/2,SEEK_SET);
lseek(fb,len/2,SEEK_SET);
char str[len/2];
ssize_t ret=0;
while(1)
{
ret=read(fa,str,sizeof(str));
if(ret==0)
{
break;
}
write(fb,str,ret);
}
close(fa);
close(fb);
}
return 0;
}
2. 验证运行到waitpid非阻塞形式时,若子进程没退出,则子进程会不会变成僵尸进程
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, const char *argv[])
{
pid_t pwd = fork();
if(pwd> 0)
{
printf("parent pid=%d\n",getpid());
int wstatus = 0;
waitpid(-1, &wstatus, WNOHANG);
int a=(wstatus>>8)&&0xff;
printf("%d\n", a);
}
else if(pwd == 0)
{
printf("child pid=%d\n",getpid());
sleep(5);//让主先运行
printf("退出\n");
exit(0);
}
else
{
perror("fork");
return -1;
}
while(1)
sleep(1);
return 0;
}
3. 创建孤儿进程和僵尸进程
僵尸,“world”被消灭但没被父进程接收
孤儿