我的代码是共享库,它应该只有一个库实例吗?
我有一个静态变量,每次调用函数时都会更改该变量。而且似乎它一直在恢复到默认值。
我做错了什么?
我编译了它
gcc -fPIC -Wall -shared -lpam -o pam_hook.so pam_hook.c
代码:
static int is_reqest_sent=0;
int PAM_LOG_args( char * function, int argc, const char ** argv,int flags,pam_handle_t *pamh)
{
int ret = 0,i=0;
char **pam_envlist, **pam_env;
FILE * fp = fopen ("/var/log/pam_flow.log","a");
fprintf(fp,"function : %s flags %d n",function,flags);
fprintf (fp, "my PID: %d parent PID %d is_reqest_sent : %dn",
getpid(),getppid(),is_reqest_sent);
/* export PAM environment */
if (pamh!=NULL)
{
if ((pam_envlist = pam_getenvlist(pamh)) != NULL)
for (pam_env = pam_envlist; *pam_env != NULL; ++pam_env) {
fprintf(fp,"%sn",*pam_env);
free(*pam_env);
}
}
for(i=0;i<=argc-1;i++)
fprintf(fp,"%sn",argv[i]);
fclose(fp);
return ret;
}
int isRequestSent(void)
{
if(is_reqest_sent==0)
{
is_reqest_sent=1;
return 0;
}
else
{
is_reqest_sent=0;
return 1;
}
}
PAM_EXTERN int pam_sm_authenticate(pam_handle_t *pamh, int flags, int argc, const char **argv) {
const char * password=NULL;
struct passwd *pwd;
const char *user;
int pam_err=0;
PAM_LOG_args( "pam_sm_authenticate", argc, argv,flags,pamh);
printTime();
/* identify user */
pam_err = pam_get_user(pamh, &user, NULL);
if (pam_err != PAM_SUCCESS)
{
return (pam_err);
}
if ((pwd = getpwnam(user)) == NULL)
{
return (PAM_USER_UNKNOWN);
}
/*note : if user is not deefined pawsword return will be "^H$^M^?INCORRECT^@" */
pam_err = pam_get_authtok(pamh, PAM_AUTHTOK, &password , NULL);
if (pam_err!=PAM_SUCCESS)
{
return (PAM_AUTH_ERR);
}
if(isRequestSent()==0)
{
debugPrint("isRequestSent return 0");
}
return (PAM_SUCCESS);
}
PAM_EXTERN int pam_sm_open_session(pam_handle_t *pamh, int flags, int argc, const char **argv) {
PAM_LOG_args( "pam_sm_open_session ", argc, argv,flags,pamh);
debugPrint("pam_sm_open_session ","",0,pamh);
printTime();
printLogoutLoging(pamh,1);
return PAM_SUCCESS;
}
并打印我必须打印is_reqest_sent
的值和过程pid:
功能 : pam_sm_authenticate标志 1
my PID: 9521 parent PID 9514 is_reqest_sent : 0
功能 : pam_sm_open_session标志 0
my PID: 9521 parent PID 9514 is_reqest_sent : 1
功能 : pam_sm_authenticate标志 1
my PID: 9528 parent PID 9514 is_reqest_sent : 0
全局变量不共享,因为每个进程都使用自己的地址空间。代码是共享的,内存不是。
要在进程之间共享内存,请使用"共享内存"(又名SHM(。