-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.cpp
More file actions
133 lines (125 loc) · 3.19 KB
/
Copy pathtest.cpp
File metadata and controls
133 lines (125 loc) · 3.19 KB
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
#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <cstdlib>
#include <signal.h>
#include <sys/wait.h>
#include <unistd.h>
#include "timeit.h"
#define DEFAULT_NUM_FORK 1000
#define RESULT_ON 0
void do_pthread(int num);
void do_fork(int num);
static int num_fork;
static int test_type;
static int tester_ret;
using namespace std;
#if RESULT_ON
int main(int argc, char **argv){
int num_fork;
if(argc == 1){
num_fork = DEFAULT_NUM_FORK;
}
else{
num_fork = atoi(argv[1]);
}
timeit t;
t.start();
do_fork(num_fork);
t.record();
cout << num_fork << " processes forked, " << endl;
t.print_last();
t.start();
do_pthread(num_fork);
t.record();
cout << num_fork << " threads created, " << endl;
t.print_last();
return 0;
}
#else
int main(int argc, char **argv){
if(argc == 1){
num_fork = DEFAULT_NUM_FORK;
}
else{
num_fork = atoi(argv[1]);
}
cout << "Main process PID: " << getpid() << endl;
while(1){
cout << "Enter 0 for fork test, 1 for thread test.\n";
cin >> test_type;
cout << "test type: " << test_type <<endl;
pid_t pid = fork();
if(!pid){
//child
sigset_t waitset;
sigemptyset(&waitset);
sigaddset(&waitset,SIGUSR1);
sigprocmask(SIG_BLOCK,&waitset,NULL);
int sig;
int result = sigwait(&waitset,&sig);
if(result){
exit(0);
}
switch (test_type){
case 0:{
do_fork(num_fork);
return 0;
}
case 1:{
do_pthread(num_fork);
return 0;
}
default:
return 1;
}
}
else if(pid >= 1){
//parent
cout << "Tester PID: " << pid << endl;
cout << "Attach strace and enter any char to continue\n";
char dumb;
cin >> dumb;
kill(pid,SIGUSR1);
waitpid(pid, &tester_ret,0);
if(tester_ret == 0){
switch(test_type){
case 0:{
cout << "Fork " << num_fork << " process successfully\n";
break;
}
case 1:{
cout << "Create " << num_fork << " threads successfully\n";
break;
}
default: {
cout << "Invalid test type\n" ;
break;}
}
}
else{
cout << "test failed! returned: "<<tester_ret<<endl;
}
cout << "\n*******************************************************\n\n";
}
}
return 0;
}
#endif
void do_fork(int num){
for(int i=0;i<num;i++){
pid_t pid;
pid = fork();
if(!pid)
exit(0);
}
}
void * dumb(void * x){
return NULL;
}
void do_pthread(int num){
pthread_t threads[num];
for(int i=0;i<num;i++){
pthread_create(&(threads[i]),NULL,&dumb,NULL);
}
}