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

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:执行结果


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

家有工程师

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值