【发布时间】:2014-12-09 21:13:39
【问题描述】:
所以我正在尝试在子进程中为 SIGTSTP 信号实现信号处理程序。
基本上我想要实现的是:
- 启动子进程
- 让父进程等待子进程
- 在子进程上调用睡眠 x 秒。
- 在睡眠完成执行之前,我想发送一个 Ctrl+Z 信号。 这个信号应该停止子进程,但恢复父进程 过程。然后父进程应该知道 停止进程。
我使用以下命令运行它:./testsig sleep 10
这是我目前的代码:
#include<stdlib.h>
#include<stdio.h>
#include<signal.h>
#include<string.h>
volatile sig_atomic_t last_proc_stopped;
volatile sig_atomic_t parent_proc_id;
void handle_stp(int signum)
{
if(getpid()==parent_proc_id)
{
kill(parent_proc_id,SIGCONT);
signal(SIGTSTP,handle_stp);
}
else
{
last_proc_stopped=getpid();
kill(parent_proc_id,SIGCONT);
}
}
void main(int argc, char *argv[])
{
int childid=0,status;
signal(SIGTSTP,SIG_IGN);
parent_proc_id=getpid();
childid=fork();
if(childid>=0)
{
if(childid==0)//child
{
signal(SIGTSTP,handle_stp);
strcpy(argv[0],argv[1]);
strcpy(argv[1],argv[2]);
argv[2]=NULL;
printf("Passing %s %s %s\n",argv[0],argv[1],argv[2]);
execvp(argv[0],argv);
}
else
{
wait(&status);
printf("Last Proc Stopped:%d\n",last_proc_stopped);
}
}
else
{
printf("fork failed\n");
}
}
目前看来 ctrl+Z 有某种效果(但绝对不是我想要的!)
当我在执行睡眠的子进程中间按 ctrl+Z 时,光标会继续闪烁(在我的情况下为 10 秒)的剩余时间,但控制不会到达父进程。
不按 ctrl+Z,控制按预期返回父级。
我做错了什么?
我也看到了这个答案,但我真的无法理解:
After suspending child process with SIGTSTP, shell not responding
【问题讨论】:
标签: c linux unix process signals