- 论坛徽章:
- 0
|
我用管道实现了 find /|grep a 命令,想按下Ctrl+Z时将命令结束,所以把find和grep加到了一个进程组里。但是调用函数ctrl_z后,这两个命令是停止了但主程序不结束,这是为什么呢?请各位指点一下,谢谢。
- /*
- * 实现 find /|grep a,可以在按下 Ctrl+Z 时正常结束
- */
- #include <stdio.h>
- #include <unistd.h>
- #include <sys/wait.h>
- #include <signal.h>
- int fgpgid;//find 和 grep 要加入的进程组号
- void ctrl_z(int);
- int main()
- {
- pid_t pids[10];
- int pipes[10][2];
- char *find[] = {"find", "/", NULL};
- char *grep[] = {"grep", "a", NULL};
- signal(SIGTSTP, ctrl_z);
- if(pipe(pipes[0]) == -1){
- printf("pipe error\n");
- }
- if((pids[1] = fork()) == -1){
- perror("fork error");
- } else if(pids[1] == 0){
- //输入
- close(pipes[0][1]);
- dup2(pipes[0][0], STDIN_FILENO);
- close(pipes[0][0]);
- //设置新的进程组,以脱离main所在的进程组
- if(setpgid(0, 0) == -1){
- printf("in child, %s setpgid error\n", grep[0]);
- }
- fgpgid = getpgid(0);
- if(execvp(grep[0], grep) == -1){
- printf("exec %s failed\n", grep[0]);
- }
- } else if(pids[1] > 0){
- //设置新的进程组,以脱离main所在的进程组
- fgpgid = pids[1];
- if(setpgid(pids[1],pids[1]) == -1){
- printf("in parent, %s setpgid error\n", grep[0]);
- }
- //printf("comm: %s, pid: %d, pgid: %d\n", grep[0], pids[1], getpgid(pids[1]));
- }
- if((pids[0] = fork()) == -1){
- perror("fork error");
- } else if(pids[0] == 0){
- //输出
- close(pipes[0][0]);
- dup2(pipes[0][1], STDOUT_FILENO);
- close(pipes[0][1]);
- //执行
- if(setpgid(0, fgpgid) == -1){
- printf("in child, %s setpgid error\n", find[0]);
- }
- if(execvp(find[0], find) == -1){
- printf("exec %s failed\n", find[0]);
- }
- } else if(pids[0] > 0){
- if(setpgid(pids[0], fgpgid) == -1){
- printf("in parent, %s setpgid error\n", find[0]);
- }
- //printf("comm: %s, pid: %d, pgid: %d\n", find[0], pids[0], getpgid(pids[0]));
- waitpid(pids[0], NULL, 0);
- }
- close(pipes[0][0]);
- close(pipes[0][1]);
- waitpid(pids[1], NULL, 0);
- return 0;
- }
- void ctrl_z(int signo)
- {
- kill(-fgpgid, SIGSTOP);
- printf("kill confirmed\n");
- }
复制代码 |
|