-
Notifications
You must be signed in to change notification settings - Fork 0
/
emul.c
148 lines (122 loc) · 2.63 KB
/
emul.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
#define MAIN
#include "common.h"
int main ( int argc, char * argv[] )
{
int i = 0, iTranNum = 1, iPnum = 1, iSuCount = 0, iRet = 0;
char caTranCode[10+1];
pid_t * pArr = NULL;
pthread_mutexattr_t mAttr;
pid_t tempid = 0;
int tempnum = 0;
memset ( caTranCode, 0x00, sizeof caTranCode );
switch ( 4 - argc )
{
case 0 :
iPnum = atoi ( argv[3] );
case 1 :
iTranNum = atoi ( argv[2] );
case 2 :
strcpy ( caTranCode, argv[1] );
break;
default :
printf ( "Usage : %s 交易码 [单个进程笔数] [进程数]\n" );
return -1;
}
pArr = ( pid_t * ) malloc ( iPnum * sizeof ( pid_t ) );
if ( ! pArr )
{
printf ( "malloc分配出错\n" );
return -1;
}
memset ( pArr, 0x00, iTranNum * sizeof ( pid_t ) );
g_sh_suCount = ( int * ) makeShareMemory ( sizeof ( int ) );
if ( ! g_sh_suCount )
{
printf ( "g_sh_suCount makeShareMemory分配出错\n" );
return -1;
}
g_sh_myLock = ( pthread_mutex_t * ) makeShareMemory ( sizeof ( pthread_mutex_t ) );
if ( ! g_sh_myLock )
{
printf ( "g_sh_myLock makeShareMemory分配出错\n" );
return -1;
}
iRet = pthread_mutexattr_init ( &mAttr );
if ( iRet )
{
printf ( "pthread_mutexattr_init出错\n" );
return -1;
}
iRet = pthread_mutexattr_setpshared ( &mAttr, PTHREAD_PROCESS_SHARED );
if ( iRet )
{
printf ( "pthread_mutexattr_setpshared出错\n" );
return -1;
}
iRet = pthread_mutex_init ( g_sh_myLock, &mAttr );
if ( iRet )
{
printf ( "pthread_mutex_init出错\n" );
return -1;
}
for ( i = 0; i < iPnum; i++ )
{
pArr[i] = fork ();
if ( pArr[i] < 0 )
{
printf ( "fork fail\n" );
return -1;
}else if ( ! pArr[i] )
{
iRet = dealTran ( caTranCode, iTranNum );
if ( iRet < 0 )
{
/* printf ( "dealTran fail\n" ); */
exit ( -1 );
}
exit ( 0 );
}
}
while ( 1 )
{
if ( tempnum >= iPnum )
break;
tempid = waitpid ( -1, NULL, WNOHANG | WUNTRACED | WCONTINUED );
if ( tempid < 0 )
{
printf ( "waitpid error\n" );
break;
}else if ( ! tempid )
{
sleep ( 1 );
continue;
}else
{
for ( i = 0; i < iPnum; i++ )
{
if ( pArr[i] == tempid )
{
tempnum++;
break;
}
}
}
}
iRet = pthread_mutex_destroy ( g_sh_myLock );
if ( iRet )
{
printf ( "pthread_mutex_destroy出错\n" );
return -1;
}
iRet = pthread_mutexattr_destroy ( &mAttr );
if ( iRet )
{
printf ( "pthread_mutexattr_destroy出错\n" );
return -1;
}
iSuCount = *g_sh_suCount;
printf ( "交易成功了 %.2f%%\n", ( ( float )iSuCount / ( iPnum * iTranNum ) ) * 100.0f );
destoryShareMemory ( g_sh_myLock, sizeof ( pthread_mutex_t ) );
destoryShareMemory ( g_sh_suCount, sizeof ( int ) );
return 0;
}