Linux进程突然挂死,当主进程突然死亡时,我该如何杀死linux spawnProcess?

本文介绍了一个简单的Linux下创建子进程的方法,并展示了如何确保子进程随父进程的退出而终止。通过D编程语言实现,代码示例包含了fork、prctl及execve等系统调用的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下面是一些将在Linux上执行的代码。它没有stdlib的spawnProcess的所有功能,它只是显示了基本的基础知识,但是如果你需要更多的东西,从这里扩展它并不难。

import core.sys.posix.unistd;

version(linux) {

// this function is Linux-specific

import core.stdc.config;

import core.sys.posix.signal;

// we can tell the kernel to send our child process a signal

// when the parent dies...

extern(C) int prctl(int, c_ulong, c_ulong, c_ulong, c_ulong);

// the constant I pulled out of the C headers

enum PR_SET_PDEATHSIG = 1;

}

pid_t mySpawnProcess(string process) {

if(auto pid = fork()) {

// this branch is the parent, it can return the child pid

// you can:

// import core.sys.posix.sys.wait;

// waitpid(this_ret_value, &status, 0);

// if you want the parent to wait for the child to die

return pid;

} else {

// child

// first, tell it to terminate when the parent dies

prctl(PR_SET_PDEATHSIG, SIGTERM, 0, 0, 0);

// then, exec our process

char*[2] args;

char[255] buffer;

// gotta copy the string into another buffer

// so we zero terminate it and have a C style char**...

buffer[0 .. process.length] = process[];

buffer[process.length] = 0;

args[0] = buffer.ptr;

// then call exec to run the new program

execve(args[0], args.ptr, null);

assert(0); // never reached

}

}

void main() {

mySpawnProcess("/usr/bin/cat");

// parent process sleeps for one second, then exits

usleep(1_000_000);

}

所以下级功能需要使用,但Linux确实有一个功能,做你所需要的。

当然,因为它发出了一个信号,你的孩子可能要处理,要关闭更优雅比默认的终止,但试试这个程序并运行ps而它睡觉,看cat运行,然后注意到猫死时父母退出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值