IOday5

作业一,父进程拷贝图片前半部分,子进程拷贝图片后半部分

#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; 
} 
~ 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值