C語言實現可變引數列表的system介面:巨集__VA_ARGS__

Koma_Wong發表於2018-11-18

目錄

t_shell.h

t_shell.c

效果


t_shell.h

/*	file name: 		t_shell.h
 *	author:			Rong Tao
 *	create time:	2018.11.14
 * 	
 */
#ifndef _T_SYS_SHELL_CMD_H_
#define _T_SYS_SHELL_CMD_H_

#ifndef _T_SHELL_STRING_MAXLEN_
#define _T_SHELL_STRING_MAXLEN_		1024
#endif 

#define t_sh_cmd(fmt, ...) _t_execfmt2string_(NULL, fmt, __VA_ARGS__)

/**
 *	Execute a format string by shell command
 *	Author: rongtao
 *	Time:	2018.11.15
 *
 */
int _t_execfmt2string_(char *string, const char *fmt, ...);


#endif /*<_T_SYS_SHELL_CMD_H_>*/

t_shell.c

/*	file name: 		t_shell.c
 *	author:			Rong Tao
 *	create time:	2018.11.15
 *	create time:	2018.11.17
 * 	
 */

#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <stdlib.h>
#include <malloc.h>
#include <unistd.h>
#include <sys/types.h>
#include <dirent.h>
#include <pwd.h>
#include <grp.h>
#include <libgen.h> 

#include "t_shell.h"
#include "t_user.h"

#define t_shell_getlogin() getlogin()
#define t_shell_getcwd(buf,size) getcwd(buf,size)

#ifndef _T_SHELL_COLOR_RED__
#define _T_SHELL_COLOR_RED__ "\033[31m"
#endif 
#ifndef _T_SHELL_COLOR_GREEN__
#define _T_SHELL_COLOR_GREEN__ "\033[32m"
#endif
#ifndef _T_SHELL_COLOR_END__
#define _T_SHELL_COLOR_END__ "\033[0m"
#endif

FILE *t_fp_sys_shell;

/**
 *	Execute a format string by shell command
 *	Author: rongtao
 *	Time:	2018.11.15
 *
 */
int _t_execfmt2string_(char *string, const char *fmt, ...)
{
	if((string = (char*)malloc(_T_SHELL_STRING_MAXLEN_)) == NULL)
	{
		return -1;
	}

	va_list arg;
	va_start(arg, fmt);

	vsprintf(string, fmt, arg);

	va_end(arg);

	char folder[_T_SHELL_STRING_MAXLEN_];
	t_shell_getcwd(folder, _T_SHELL_STRING_MAXLEN_);

	char *user = t_getcurrentusername(NULL);
	char *grp = t_getcurrentgrpname(NULL);
	char *shell = t_getcurrentusershell(NULL);


	fprintf(stdout, "%s[%s@%s-%s %s]%c %s", 
		strcmp(user, "root")==0?_T_SHELL_COLOR_RED__:_T_SHELL_COLOR_GREEN__,
		user,grp,
		basename(shell), 
		basename((char*)folder), strcmp(user, "root")==0?'#':'$',
		_T_SHELL_COLOR_END__);
	
	fprintf(stdout, "%s\n", string);
	
	system(string);
	
	free(string);
	free(user);
	free(grp);
	free(shell);
	
	return 0;
}





#if 1
int main()
{

	t_sh_cmd("ls %s; mkdir %s; rm -rf %s", "/home/rongtao", "1a.out", "1a.out");
}
#endif

效果

$ gcc t_shell.c t_user.c
$ ./a.out 
$ ls /home/rongtao; mkdir 1a.out; rm -rf 1a.out
clean.sh  文件

實際上的效果

今天發現個好玩的linux註釋:

相關文章