当我这样做时
pid_t pid = fork();
...
if (pid == 0)
execvp(...);
...
if (pid > 0) {
kill(pid, SIGTERM);
}
它会杀死孩子,没关系, 但它也会杀死父进程(不确定这是否重要,但父进程有自定义的 sig 处理程序)。
这是正确的行为吗?或者我做错了什么? 如何防止父进程被杀死?
预期的逻辑是,如果父级在预定义的时间范围内没有收到某些通知,则停止子级。然后再次运行新的子实例
对我来说效果很好:
int main(void)
{
pid_t child_pid = fork();
if (child_pid == -1)
{
perror("fork failed");
exit(1);
}
else if (child_pid == 0)
{
// In the child process
printf("Child process started with PID %d\n", getpid());
while (1)
{
printf("Child is running...\n");
fflush(stdout);
usleep(1000);
}
}
else
{
// In the parent process
printf("Parent process with PID %d created child with PID %d\n", getpid(), child_pid);
// Give the child some time to run
usleep(35000);
// Terminate the child process
printf("Parent is killing the child process...\n");
kill(child_pid, SIGTERM);
waitpid(child_pid, NULL, 0);
printf("Child process terminated. Parent continues...\n");
// The parent process continues running
}
return 0;
}