|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
输入ctrl + c ,程序打印了一部分没有执行, 设p2 = 0 while 循环没有退出
运行环境 ubantu 编译器 g++
- #include <unistd.h>
- #include <iostream>
- #include <string>
- #include <signal.h>
- #include <sys/wait.h>
- #include <sys/types.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);
- cout << "创建子进程——1成功 " ;
- childPid_1 = getpid ();
- cout << "ppid "
- << getppid()
- << " pid "
- << getpid()
- << endl;
- while (i){
- /*执行子进程-1操作**/
- send = send1+to_string(i);
- send += send2;
- const char* s = send.c_str();
- i++;
- write(pfd[1],s,1024);
- /* 每发送一次 休眠一秒*/
- sleep(1);
- //捕捉父进程的信号,退出循环
- if (signal(SIGUSR1,process_cap1) == SIG_ERR){
- cout << "error";
- }
-
-
- }
-
-
- 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);
-
- cout << "创建子进程——2成功" ;
- childPid_2 = getpid();
- cout << " ppid "
- << getppid()
- << " pid "
- << getpid()
- << endl;
- /*执行子进程-2操作**/
- while (j){
- read(pfd[0],buf,1024);
- cout << buf << endl;
- //捕捉父进程信号
- if (signal (SIGUSR2,process_cap2) == SIG_ERR) {
- cout << "error";
- }
- 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 ;
- }
复制代码 |
|