linux应用编程:signal(信号量) 实例1

时间:2022-04-28 15:16:22

1:示例代码

#include<stdio.h>
#include<fcntl.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
#include<signal.h>
#include<stdlib.h>
#include <sys/wait.h>
//the copy fie size must>M
int count=0;				//current copy number
int file_size;			//the file size
pid_t pid;
void sig_alarm(int arg)
{
	kill(pid,SIGUSR1);
}
void sig_int(int arg)
{
	printf("file size:%d totalreceive size:%d\n",file_size,count);
	exit(EXIT_SUCCESS);
}
char bar[10000];
void sig_usr(int sig)
{
	float i;
	strcat(bar,"#");
    fflush(stdout);
	i=(float)count/(float)file_size;
	//printf("curent over :%0.0f%%\n",i*100);
	printf("curent over :%s %0.0f%%\n",bar,i*100);
}


int main(int argc,char *argv[])
{
	int i=0,stat_val;;
	int fd_src,fd_des;
	char buf[4096];		//in order to infirm the problem, buf can set small
	if(argc!=3)
	{
		printf("check the format:comm src_file des_file\n");
		return -1;
	}
	if((fd_src=open(argv[1],O_RDONLY) )==-1 )
	{
		perror("open file src");
		exit(EXIT_FAILURE);
	}

	file_size=lseek(fd_src,0,SEEK_END);
	lseek(fd_src,0,SEEK_SET);

	if( (fd_des=open(argv[2],O_RDWR|O_CREAT,0644) )==-1 )
	{
		perror("open fd_fdes");
		exit(EXIT_FAILURE);
	}

	if( (pid=fork())==-1)
	{
		perror("fork");
		exit(EXIT_FAILURE);
	}
	else if(pid==0)
	{	printf("1pid();%d ppid%d\n",getpid(),getppid());
		signal(SIGUSR1,sig_usr);
		do
		{
			memset(buf,'\0',sizeof(buf));
			if((i=read(fd_src,buf,sizeof(buf)))==-1)	//the copy number may modify
			{
				perror("read");
				exit(EXIT_FAILURE);
			}
			else if(i==0)
			{
			//	perror("kill");
				kill(getppid(),SIGINT);
				break;
			}
			else
			{
				if(write(fd_des,buf,i)==-1)
				{
					perror("write");
					exit(EXIT_FAILURE);
				}
				count+=i;
			}
		}while(i!=0);
		waitpid(pid,&stat_val,0);
		if(WIFEXITED(stat_val))
		{
			printf("Child exited with code %d count:%d\n", WEXITSTATUS(stat_val),count);
		}
		else if (WIFSIGNALED(stat_val))
		{
			printf("Child terminated abnormally, signal %d count:%d\n", WTERMSIG(stat_val),count);
		}
		exit(EXIT_SUCCESS);
	}
	else if(pid>0)
	{
			signal(SIGALRM,sig_alarm);
			signal(SIGINT,sig_int);
#if 0
			ualarm(250000,200000);	//if alarm ,in sig_alarm function to install again
#endif
			while(1)
			{
#if 0
					alarm(1);	//if alarm ,in sig_alarm function to install again
					pause();
#endif
#if 0
					kill(pid,SIGUSR1);
					usleep(250000);
#endif
					kill(pid,SIGUSR1);
					sleep(2);
			}

			exit(EXIT_SUCCESS);
	}

}



2:执行结果

linux应用编程:signal(信号量) 实例1