day5 IO进程 c语言

1. 拷贝一张图片,父进程拷贝一半,子进程拷贝另一半

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
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 <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
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 <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
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 <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值