陷阱命令未在 /bin/sh 脚本中触发

问题描述 投票:0回答:1

我有一个 /bin/sh 脚本,其中包含如下所示的 trap 命令。

#!/bin/sh

# Define signal handler function
sigint_handler() {
    echo "Received SIGTERM signal."
    exit 1
}

# Set up signal handler
trap sigint_handler TERM

# Wait for a signal
echo "Waiting for signal..."
while [ 1 ]
do
sleep 4m&
p="$!"
wait
unset p

done

如果我独立运行该脚本,它会按预期工作。 如果我用 kill -15 pid 杀死 打印“收到 SIGTERM 信号”。 如果我使用 execvp 从 C++ 程序启动相同的脚本,脚本会启动但不会触发陷阱 下面是生成进程并将 pids 返回给调用者的 c++ 函数。 注意:- 这个函数是从多个线程调用的。

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <stdio.h>      /* for 'printf' and 'NULL' */
#include <stdlib.h>     /* for 'errno' */
#include <errno.h>

pid_t fork_process (pid_t &new_pid,string process_start(here test.sh)){
    int pid;
    int status;

    printf("Parent: %d\n", getpid());
char *args[]={"./test.sh",NULL}
    pid = fork();
    if (pid == 0){
        printf("Child %d\n", getpid());
    int r=execvp(args[0],args);
 if (r < 0) {

        const int err = errno;

      printf( "exec failed with errno: %d", err);
      exit(err);
    }
    }

     pid=waitpid(pid, &status, WNOHANG);
    printf("%d\n",pid);

有什么建议吗?

使用来自 c/c++ 代码的 execvp 启动 /bin/sh 脚本,陷阱未在脚本中触发

c++ linux bash signals
1个回答
1
投票

exec() 系列函数用新的过程映像替换当前过程映像,因此通过调用 execvp(),您的其余 C 代码将不再存在。

使用 spawn() 系列之一来启动 CHILD 进程。

© www.soinside.com 2019 - 2024. All rights reserved.