【发布时间】:2019-12-04 20:56:29
【问题描述】:
我正在我的 shell 中创建一个带有 fork 的子进程,并分配这个子进程来执行一个 cmd,例如:“ls -lR /”,就像你在我的代码中看到的那样,使用 'execve()',当我收到 SIGTSTP,我想用kill(child_process, SIGTSTP) 停止这个子进程,当你输入“fg”命令时,我必须用kill(child_process, SIGCONT) 重置这个运行的子进程,问题是wait(&status) 在我收到 SIGTSTP 后永不返回仍在等待子进程结束,
-- 那我该怎么做呢??
#include <signal.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
int child_pid;
int parn_pid;
void func1(int sig)
{
kill(child_pid, SIGTSTP);
}
int main()
{
int sig;
int status;
char *argv[] = {"ls", "-lR", "/", NULL};
signal(SIGTSTP, func1);
child_pid = fork();
if (child_pid == 0)
{
child_pid = getpid();
execve("/bin/ls", argv, NULL);
exit (1);
}
else
{
parn_pid = getpid();
waitpid(child_pid, &status, WUNTRACED);
printf("\nsuspended\n");
if (WIFSTOPPED(status))
{
sleep(2);
kill(child_pid, SIGCONT);
wait(&status);
}
}
return (0);
}
【问题讨论】:
-
开启编译器警告:
warning: result of comparison of constant 18 with boolean expression is always false [-Wtautological-constant-out-of-range-compare] if (WIFSIGNALED(status) == SIGTSTP) -
您使用 WIFSIGNALED 不正确,因此从不发送 SIGCONT。
-
解决了,但是 printf 从来没有放 "\nsuspended\n" 这意味着等待仍在等待孩子结束。