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
| #include<iostream> #include <sys/types.h> #include <unistd.h> #include <chrono> #include <thread> #include <sys/ipc.h> #include <sys/msg.h> #include <set> #include <signal.h> #include <csignal> #include <sys/ipc.h> #include <sys/msg.h> #include <string.h> #include <string> #include <sys/wait.h> using namespace std;
volatile std::sig_atomic_t sig_num = 0;
void signalHandler( int signum ) { for (int i = 0; i < 100000; i++) { std::this_thread::sleep_for(std::chrono::seconds(1)); std::cout << "Fuck Break:" <<" i:"<<i<<" sig:"<< signum <<" pid:"<<getpid()<< std::endl; } }
int main(int argc, char * argv[]) { pid_t main_pid = -1; struct msg { long mtype; char mmsg[1024]; } msg;
key_t key = key_t(1122); int qid = msgget(key, IPC_CREAT | IPC_EXCL | 0666); if (qid != -1) { std::cout << "create msg" << std::endl; } else { std::cout << "alreaty have" << std::endl; msgctl(qid, IPC_RMID, NULL); }
pid_t mpid = fork(); if (mpid == 0) { main_pid = getppid();
for (int i = 0; i < 3; ++i) { pid_t pid1 = fork();
if (pid1 == -1) return -1; else if (pid1 == 0) { std::cout << "#############################I:" << i << "T pid:" << getpid() << std::endl; signal(SIGUSR1, signalHandler); memset(msg.mmsg, 0, 1024); std::string id_str = std::to_string(getpid());
memcpy(msg.mmsg, id_str.c_str(), id_str.length() ); std::cout << "msgsnd Msg:" << msg.mmsg << std::endl; msgsnd(qid, &msg, 1024, 0);
break;
} else {
} }
} else {
struct rmsg { long type; char buffer[1024]; } rmsg; std::this_thread::sleep_for(std::chrono::seconds(5)); std::cout << "r qid:" << qid << std::endl; msqid_ds msg_info; auto how = [&]() -> bool { if (!msgctl(qid, IPC_STAT, &msg_info)) { std::cout << "qnum:" << msg_info.msg_qnum << std::endl; if (msg_info.msg_qnum) { return true; } else { return false; } } };
std::set<pid_t>pool_;
do { msgrcv(qid, &rmsg, 1024, 0, 0); std::cout << "msgrcv Msg:" << rmsg.buffer << std::endl; pool_.insert(std::stoi(rmsg.buffer)); } while (how());
msgctl(qid, IPC_RMID, NULL); std::cout << "pid_ start" << std::endl; { for (auto one : pool_) { std::cout << "PoocessID:" << one << std::endl; kill(one, SIGUSR1); } }
int status; wait(&status);
} return 0; }
|