【问题标题】:how i can suspend child process and reset it我如何暂停子进程并重置它
【发布时间】: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" 这意味着等待仍在等待孩子结束。

标签: c fork wait execve


【解决方案1】:

您需要使用waitpid() 而不是wait()。使用wait() 将等待子进程终止,这意味着进程必须已退出,例如从 SIGKILL 或 SIGSEGV。您正在尝试等待进程停止,这不是一回事。停止一个进程只是暂停它,它允许它稍后继续。它不会退出。

您需要使用WUNTRACED 标志和waitpid() 来等待子进程被终止或停止。如waitpid(child_pid, &amp;status, WUNTRACED)waitpid(-1, &amp;status, WUNTRACED)

还有一个与此相关的缺陷。 WIFSIGNALLED()WTERMSIG() 也仅适用于被信号终止的处理。您应该改为使用WIFSTOPPED()WSTOPSIG() 来检测孩子是否停止。

另请注意:

  • SIGSTOP 也可以停止进程。
  • 您可能会在设置信号处理程序后的任何时间收到SIGTSTP,这可能是在为child_pid 分配值之前。
  • 如果您的进程被信号中断,wait() 和朋友可以返回 -1 并将 errno 设置为 EINTR

【讨论】:

  • 您的回答非常有帮助,它解决了我的问题,感谢您分享此信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-22
  • 1970-01-01
  • 2022-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多