gpt4 book ai didi

c - waitpid() 不允许将 SIGINT 发送到子进程?

转载 作者:太空宇宙 更新时间:2023-11-04 03:05:56 26 4
gpt4 key购买 nike

#include <stdio.h>
#include <string.h>
#include <strings.h>
#include <limits.h>
#include <unistd.h>
#include <stdlib.h>
#include <pwd.h>
#include <dirent.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>


void sig_handler(int signal);

int pid, forkFlag = 0;

int main( int argc, char **argv, char **envp )
{
sigset(SIGINT, sig_handler); //handle ctrl + c
sigignore(SIGTSTP);
sigignore(SIGSTOP);

int ex, rv, status;
forkFlag = 1; //fork is being called

pid = fork();

if(pid == -1){

perror("fork");
exit(2);
}
else if (pid == 0){ //if child process

ex = access(argv[0], X_OK); //check if file is executable

if(ex){

perror("access");
exit(1);
}
else{
rv = execve(argv[0], argv, envp); //run program in child process

if(rv == -1){

perror("execve");
exit(1);
}
}
exit(0); //end child process
}
else{
rv = waitpid(pid, &status, 0); //wait for child

if(rv == -1){

perror("waitpid");
}

if(WEXITSTATUS(status)){ //check status of child if it did ot return 0

printf("The return status of the child was %d\n", WEXITSTATUS(status));
}
}
forkFlag=0;
}

void sig_handler(int signal)
{
if(signal == SIGINT && (pid && forkFlag)){

kill(pid,signal); //send kill to child
}
}

我试图让我的程序忽略 ctrl + C,除非有子进程正在运行,然后它会将 SIGINT 发送到子进程。但是,当我在子进程运行时按 ctrl + c 时,waitpid() 返回 -1 并显示错误“系统调用中断”。这使得子进程停止运行,但如果我使用 ps,子进程仍然存在,但现在标记为已失效。我从 printf 语句知道 kill 正在调用函数 sig_handler,并且 pid 和 forkFlag 是它们的正确值。 waitpid() 是否让我的程序忽略了杀戮?我该如何解决?我知道这段代码几乎什么都不做,但它只是我代码的一小部分(唯一涉及 fork 的部分)

感谢您的帮助。

最佳答案

问题是子进程为 SIGINT 获得相同的覆盖处理程序。您可能希望在 fork 之后重置子进程中的信号处理程序,或者您可能希望在已经 fork 子进程之后在父进程中安装信号处理程序,这样它就不会继承覆盖的处理程序。

关于c - waitpid() 不允许将 SIGINT 发送到子进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5189817/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com