回复别人要点 "回复" 按钮,不然别人是收不到通知的,除非别人主动点进来。
#include <iostream>
#include <signal.h>
#include <string>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
using namespace std;
pid_t childPid_1;
pid_t childPid_2;
int i = 1;
bool j = true;
/*处理信号函数*/
void cap(int signum);
void process_cap1(int signum);
void process_cap2(int signum);
int main(int argc, char *arg[]) {
int pfd[2];
char buf[1024];
string send1 = "I send you ";
string send2 = " time";
string send;
/*创建匿名管道*/
if(pipe(pfd) == -1) {
cout << "创建失败" << endl;
} else {
cout << "创建管道成功" << endl;
}
childPid_1 = fork();
if(childPid_1 < 0) {
cout << "创建失败" << endl;
} else {
if(childPid_1 == 0) {
//忽略SIGINT
signal(SIGINT, SIG_IGN);
// //捕捉父进程的信号,退出循环
//捕捉父进程的信号
if(signal(SIGUSR1, process_cap1) == SIG_ERR) {
cout << "error";
}
cout << "创建子进程——1成功 ";
childPid_1 = getpid();
cout << "ppid " << getppid() << " pid " << getpid() << endl;
while(i) {
/* 每发送一次 休眠一秒*/
sleep(1);
/*执行子进程-1操作**/
send = send1 + to_string(i);
send += send2;
//const char *s = send.c_str();
i++;
//write(pfd[1], s, 1024);
write(pfd[1], send.c_str(), send.size());
/* 每发送一次 休眠一秒*/
//sleep(1);
}
cout << "Child Process 1 is killed by Parent" << endl;
exit(0);
} else {
// sleep(5);
/*执行父进程创建子进程-2操作*/
childPid_2 = fork();
if(childPid_2 < 0) {
cout << "创建失败" << endl;
} else if(childPid_2 == 0) {
//忽略SIGINT
signal(SIGINT, SIG_IGN);
//捕捉父进程信号
if(signal(SIGUSR2, process_cap2) == SIG_ERR) {
cout << "error";
}
cout << "创建子进程——2成功";
childPid_2 = getpid();
cout << " ppid " << getppid() << " pid " << getpid()
<< endl;
/*执行子进程-2操作**/
while(j) {
/*
read(pfd[0], buf, 1024);
cout << buf << endl;
*/
size_t nbytes = read(pfd[0], buf, 1024);
cout << std::string(buf, buf + nbytes) << endl;
sleep(1);
if(j == false) {
break;
}
}
cout << "Child Process 2 is killed by Parent!" << endl;
exit(0);
} else {
/*执行来自用户的操作 ctrl+c */
signal(SIGINT, cap);
while(true)
;
}
}
}
}
void cap(int signum) {
cout << getpid() << "进程"
<< "捕捉到SIGINT信号" << endl;
kill(childPid_1, SIGUSR1);
waitpid(childPid_1, NULL, 0);
kill(childPid_2, SIGUSR2);
waitpid(childPid_2, NULL, 0);
cout << "Parent Process is killed";
signal(SIGINT, SIG_DFL);
}
void process_cap1(int signum) {
cout << getpid() << "进程"
<< "捕捉到SIGUSR1信号" << endl;
//将 i 设置为负数 退出while
i = -1;
}
void process_cap2(int signum) {
cout << j;
j = false;
cout << getpid() << "进程"
<< "捕捉到SIGUSR2信号" << endl;
cout << j;
return;
}
|