C实现LINUX命令行环境下的进度条功能

虽然Linux通过命令行操作时非常方便的,但是有时候那又臭又长的脚本执行过程的各种输出也实在看着乱七八糟,因此用C语言写了一个简单的进度条,因为是根据我自己的项目写的,所以只是单纯的循环进度条,而不是根据百分比显示。大神自己修改哦!


#include <stdio.h>  
#include <string.h>  
#include <unistd.h>
#include <signal.h> 
#include <sys/types.h>
#include <errno.h>
#include <sys/wait.h>

void proc(pid_t pid);
void start_proc(char* tip,pid_t pid);

void proc(pid_t pid)  
{ 	
	int i,j;
	char fh[] = {'-','-','\\','\\','|','|','/','/'};
	while(1){
		for (j = 1; j <= 50; ++j)  
		{  		
			
			printf("\r进度:[ "); 
			for (i = 1; i <= 50; ++i)  
			{  
				if(i==j){
					printf("\033[34m#\033[0m");  
				}else{
					printf("\033[33m-\033[0m");  
				}		
			}  	  	
			printf(" ] [ \033[34m %c runing...\033[0m ]",fh[j%8]); 
			fflush(stdout);
			usleep(50*1000);
			int status;
			if(waitpid(pid, &status, WNOHANG) == pid){
				printf("\r进度:[ "); 
				for (i = 1; i <= 50; ++i)  
				{ 
					printf("\033[34m#\033[0m");  
				}  	  	
				if(errno != EINTR){
					printf(" ] [ \033[32m    done    \033[0m ]");
				}else{
					printf(" ] [ \033[32m    done    \033[0m ]"); 	
				}
				fflush(stdout);
				return;
			}
		}  	
	}
}  
  
void start_proc(char* tip,pid_t pid)  
{  		

	printf("%s     PID:%d\n",tip,pid); 
	proc(pid) ;
	printf("\n");
}  
int main()  
{  		
	pid_t pid;
	pid = fork();
	
	if(pid < 0){
		printf("当前进程出错\n");
	}else if(pid == 0){
		int i =0;
		
		sleep(10);
		
		 return 0;
	}else{
		//while(kill(0,pid) != 0);
		start_proc("正在初始化环境....",pid);
	}
    return 0;  
}  



效果如下




怎么样?还阔以吧?!

猜你喜欢

转载自blog.csdn.net/qq_28347599/article/details/74321018